Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

  1. Customer has added Expresso with mocha and milk.

  2. Now the Expresso is decorated with mocha and milk.

  3. Suddenly the customer want to replace mocha with Whip.

like image 621
Abcoa Avatar asked Dec 09 '25 21:12

Abcoa


2 Answers

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.

like image 129
Thomas Stets Avatar answered Dec 11 '25 11:12

Thomas Stets


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());
like image 34
Benjamin Gale Avatar answered Dec 11 '25 09:12

Benjamin Gale



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!