我如何从对象中移除装饰器?

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);

编辑:场景是

  • 客户已经将Expresso加入了摩卡和牛奶。

  • 现在Expresso装饰着摩卡和牛奶。

  • 突然,顾客想用鞭子取代摩卡。


  • 您必须为自己提供逻辑,如下所示:

    CondimentDecorator#removeCondiment(Class <? extends CondimentDecorator>)
    

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


    如果不写一个定制的装饰器来处理这个,你就不能。 除了删除装饰器,你可以重新创建饮料减去Mocha装饰器

    beverage = new Milk(new Espresso());
    
    链接地址: http://www.djcxy.com/p/5491.html

    上一篇: How can I remove a decorator from an object?

    下一篇: Loadmanager onLoadFinished not called