如何从对象中删除装饰器?

时间:2014-11-03 12:00:17

标签: java linked-list decorator

public abstract class Beverage {

    protected String Description; 

    public String getDescription(){
        return Description;
    }

    public abstract int cost();

}

public class Espresso extends Beverage{

    public int cost(){
        return 2;
    }
    public Espresso(){
        Description = "Espresso";
    }   
}


abstract class CondimentDecorator extends Beverage{

    public abstract String getDescription();


}

public class Mocha extends CondimentDecorator{

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

    @Override
    public String getDescription() {
        return beverage.getDescription()+", Mocha ";
    }
    @Override
    public int cost() {
        return beverage.cost()+0.5;
    }   

    public Beverage remove(Beverage b) {
        return b;
    }

}
...

还有更多的装饰品,比如牛奶,大豆......等咖啡,比如HouseBlend ......等。

如果我在物体上有摩卡牛奶装饰器,我想删除“摩卡咖啡”'装饰。

Beverage beverage = new Mocha(new Espresso());
beverage = new Milk(beverage);

编辑: 方案是

  1. 客户已添加Expresso与摩卡咖啡和牛奶。

  2. 现在,Expresso装饰着摩卡咖啡和牛奶。

  3. 突然间,客户想要用Whip替换mocha。

2 个答案:

答案 0 :(得分:1)

你必须自己提供逻辑,例如:

CondimentDecorator#removeCondiment(Class <? extends CondimentDecorator>)

让该方法检查它是否包装该类的CondimentDecorator,并直接引用包装的Beverage,绕过装饰器移除。在包装的Beverage上递归调用它包装的装饰器不匹配。

答案 1 :(得分:1)

如果不编写自定义装饰器来处理这个问题,你就不能。除了删除装饰器,您可以重新创建饮料减去Mocha装饰器

beverage = new Milk(new Espresso());