Reputation: 61
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.
Upvotes: 3
Views: 835
Reputation: 13177
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());
Upvotes: 1
Reputation: 3035
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.
Upvotes: 1