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..

if I had a Mocha Milk decorator on the object, I want to remove just the 'Mocha' decorator.

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

EDIT : the scenario is

  • Customer has added Expresso with mocha and milk.

  • Now the Expresso is decorated with mocha and milk.

  • Suddenly the customer want to replace mocha with Whip.


  • 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. Call recursively on wrapped Beverage it wrapped decorator does not match.


    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

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

    上一篇: 无法显示HTML字符串

    下一篇: 我如何从对象中移除装饰器?