How do 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 is more decorator like Milk .. Soy .. etc. and coffee like HouseBlend .. etc.

If I had a Mocha Milk decorator on an object, I only want to remove the "Mocha" decorator.

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

      

EDIT: script

  • The customer added an Expresso with mocha and milk.

  • Now Expresso is decorated with mocha and milk.

  • Suddenly the client wants to replace the mocha with a Whip.

+3


source to share


2 answers


You will need to provide logic for yourself, something like:

CondimentDecorator#removeCondiment(Class <? extends CondimentDecorator>)

      



this method checks if it terminates the CondimentDecorator of this class and references the packaged beverage directly, bypassing the remove decorator. Calling recursively on a wrapped drink that it wrapped with a decorator does not match.

+1


source


Without writing a custom decorator for this, you can't. Instead of removing the decorator, you could just recreate the drink minus the Mocha

decorator



beverage = new Milk(new Espresso());

      

+1


source







All Articles