简体   繁体   English

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

[英]How can I remove a decorator from an object?

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

}
...

there's more decorator like Milk.. Soy.. etc and coffee like HouseBlend.. etc.. 还有更多的装饰品,如牛奶,大豆......等咖啡,如HouseBlend ......等。

if I had a Mocha Milk decorator on the object, I want to remove just the 'Mocha' decorator. 如果我在对象上有一个Mocha Milk装饰器,我想删除'Mocha'装饰器。

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

EDIT : the scenario is 编辑:场景是

  1. Customer has added Expresso with mocha and milk. 客户已添加Expresso与摩卡咖啡和牛奶。

  2. Now the Expresso is decorated with mocha and milk. 现在Expresso装饰着摩卡咖啡和牛奶。

  3. Suddenly the customer want to replace mocha with Whip. 突然,客户希望用Whip替换mocha。

You'll have to provide the logic for that yourself, something like: 你必须自己提供逻辑,例如:

CondimentDecorator#removeCondiment(Class <? extends CondimentDecorator>)

have that method check whether it wraps a CondimentDecorator of that class, and reference the wrapped Beverage directly, bypassing the decorator to remove. 让该方法检查它是否包装该类的CondimentDecorator,并直接引用包装的Beverage,绕过装饰器删除。 Call recursively on wrapped Beverage it wrapped decorator does not match. 在包装的Beverage上递归调用它包装的装饰器不匹配。

Without writing a custom decorator to handle this you can't. 没有编写自定义装饰器来处理这个你不能。 Instead of removing the decorator you could just recreate the beverage minus the Mocha decorator 而不是删除装饰器,你可以重新创建饮料减去Mocha装饰器

beverage = new Milk(new Espresso());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM