Java设计模式--装饰器模式

该模式又称为包装模式,允许向一个现有的对象添加新的功能,同时又不改变其结构,就像一种装饰一样,动态的将功能附加到别的类中。其实这种模式比较常见,例如Java中的io类就是利用了这种模式。一个简单的输入输出流经过包装可以有各种功能。简单实现:

抽象类

public interface Beverage {
    void make();
}

基本实现类(被装饰对象)

public class Coffee implements Beverage{
    @Override
    public void make() {
        System.out.println("make coffee");
    }
}

装饰者

public abstract class AdditivesBeverage implements Beverage{
    private Beverage beverage;

    public AdditivesBeverage(Beverage beverage){
        this.beverage = beverage;
    }

    @Override
    public void make() {
        beverage.make();
    }
}

装饰者具体实现

public class AdvancedCoffee extends AdditivesBeverage {
    public AdvancedCoffee(Beverage beverage) {
        super(beverage);
    }

    private void addSugar(){
        System.out.println("add sugar");
    }

    private void addMilk(){
        System.out.println("add milk");
    }

    @Override
    public void make() {
        super.make();
        addSugar();
        addMilk();
    }
}

测试类

public class test {
    public static void main(String[] args) {
        AdditivesBeverage beverage = new AdvancedCoffee(new Coffee());
        beverage.make();
    }
}

你可能感兴趣的:(Java设计模式--装饰器模式)