装饰者模式应该如何理解原理?

根据我的理解可以分为已下几个关注点:

1.被装饰的抽象对象—最终装饰成什么样的一个组合体

2.被装饰对象的实现—以该抽象实例为基础与其他装饰对象为一体

3.抽象装饰器—构造参数必须传入装饰对象,所有的装饰类基础该抽象装饰器

4.装饰器对象的实现—装饰对象被装饰对象增强功能

/被装饰抽象对象:饮料
interface Drink {
    //价格
    public Integer price();

    //名称
    public String name();

    //描述
    public String desc();
}

//被装饰对象实现:咖啡
class Coffer implements Drink {
    private Integer price = 10;
    private String name = "普通咖啡";

    @Override
    public Integer price() {
        return price;
    }

    @Override
    public String name() {
        return name;
    }

    @Override
    public String desc() {
        return String.format("[%s] 价格:%d", name(), price());
    }


}

//抽象装饰器
abstract class Decoeator implements Drink {
    protected Drink drink;

    public Decoeator(Drink drink) {
        this.drink = drink;
    }

}

//牛奶装饰器
class MilkDecoeator extends Decoeator {
    private Integer price = 5;
    private String name = "牛奶";

    public MilkDecoeator(Drink drink) {
        super(drink);
    }

    @Override
    public Integer price() {
        return super.drink.price() + price;
    }

    @Override
    public String name() {
        return super.drink.name() + " + " + name;
    }

    @Override
    public String desc() {
        return String.format("[%s]  价格:%d", name(), price());
    }
}

class Sugar extends Decoeator {
    private Integer price = 1;
    private String name = "糖";

    public Sugar(Drink drink) {
        super(drink);
    }

    @Override
    public Integer price() {
        return super.drink.price() + price;
    }

    @Override
    public String name() {
        return super.drink.name() + " + " + name;
    }

    @Override
    public String desc() {
        return String.format("[%s]  价格:%d", name(), price());
    }
}

class Banana extends Decoeator {
    private Integer price = 3;
    private String name = "香蕉";

    public Banana(Drink drink) {
        super(drink);
    }

    @Override
    public Integer price() {
        return super.drink.price() + price;
    }

    @Override
    public String name() {
        return super.drink.name() + " + " + name;
    }

    @Override
    public String desc() {
        return String.format("[%s]  价格:%d", name(), price());
    }
}

测试:

  public static void main(String[] args) {
        Drink drink = new Coffer();
        System.out.println(drink.desc());
        drink = new MilkDecoeator(drink);
        System.out.println(drink.desc());
        drink = new Sugar(drink);
        System.out.println(drink.desc());
        drink = new Banana(drink);
        System.out.println(drink.desc());
    }

 

难点:为什么 价格!=上个对象+装饰对象的价格

 我们可以理解为最终装饰对象=被装饰对象+所有装饰对象的组合

 

Rick  43浏览  0评论  2020-09-26

上一篇