Jump to content


Photo

Decorator Pattern - Removing Decorator From The Decorated Object


  • Please log in to reply
1 reply to this topic

#1 Thennam Pandian

Thennam Pandian

    New Member

  • Members
  • Pip
  • 3 posts

Posted 26 September 2010 - 02:22 AM

Is it possible to remove decorator from the decorated Object?

Consider the following scenario :

1. Customer has added Expresso with mocha and soy.

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

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

In that case, we need to remove the soy from the decorated object and decorate with Whip.

How do we solve this issue with the design given in the book?

Edited by Thennam Pandian, 26 September 2010 - 02:40 AM.


#2 hgilson

hgilson

    Active Member

  • Members
  • PipPip
  • 12 posts

Posted 08 October 2010 - 10:48 AM

Here is a possible solution. Hope it helps.

Add this to Beverage Class:
public Beverage removeCondiment () {
return this;
}

Override this implementation in all the classes the implement CondimentDecorator with this.
public Beverage removeCondiment () {
return beverage;
}

Here's the test code.
System.out.println("\nTesting removing condiment");
myHouseBlend = myHouseBlend.removeCondiment();
System.out.println(myHouseBlend.getDescription() + " $" + myHouseBlend.cost());

System.out.println("\nTesting adding new condiment after removal");
myHouseBlend = new SteamedMilk(myHouseBlend);
System.out.println(myHouseBlend.getDescription() + " $" + myHouseBlend.cost());

System.out.println("\nTesting removing condiment from base drink");
Beverage testBase = new DarkRoast ();
testBase.removeCondiment();
System.out.println(testBase.getDescription() + " $" + testBase.cost());

Here is the resulting output:
Espresso $1.99
Dark Roast, Mocha, Mocha, Whip $1.49
House Blend, Soy, Mocha, Whip $1.34

Testing removing condiment (removes whip)
House Blend, Soy, Mocha $1.24

Testing adding new condiment after removal (add steamed milk)
House Blend, Soy, Mocha, Steamed Milk $1.34

Testing removing condiment from base drink (should do nothing)
Dark Roast $0.99







QUOTE (Thennam Pandian @ Sep 26 2010, 02:22 AM) <{POST_SNAPBACK}>
Is it possible to remove decorator from the decorated Object?

Consider the following scenario :

1. Customer has added Expresso with mocha and soy.

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

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

In that case, we need to remove the soy from the decorated object and decorate with Whip.

How do we solve this issue with the design given in the book?






0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users