• Post Reply Bookmark Topic Watch Topic
  • New Topic

Doubt in Design Pattern "Decorator"  RSS feed

 
shivang sarawagi
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a doubt in the main class of this pattern. I will really appreciate it if anyone helps me out. Thanks Here is the code














I am not able to understand these lines of code



How does initializing the beverage2 object several times and using the beverage2.cost() method just once gives the total of all the condiments.

The output is : Dark Roast Coffee, Mocha, Mocha, Whip $1.49
 
shivang sarawagi
Ranch Hand
Posts: 159
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I also see no use of the CondimentDecorator class, the condiments can directly extend the Beverage class
 
Stephan van Hulst
Saloon Keeper
Posts: 7969
143
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Well, as you can see, the Whip object has an internal reference to the object you're decorating. In this case, it's a Mocha. That Mocha object has a reference to another Mocha object. That one has a reference to a DarkRoast object. When you call the cost() method on the Whip object, it calculates cost by adding 10 cents to the cost of the Mocha object it decorates. The same happens for the Mocha objects.

There's no real use is asking what the point of the CondimentDecorator class is. None of the classes here have a use. It's an example.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!