views:

293

answers:

3
+9  A: 

No, they are not the same.

Head First example has 1 drink with Mocha, Whip, Roast added. Your example has 3 beverages.
See this Head First code. It works on the same instance of the beverage

beverage2 = new Mocha(beverage2);                                       
beverage2 = new DarkRoast(beverage2);                                       
beverage2 = new Whip(beverage2);

Your code creates 3 beverages (which means someone ordered 3 things separately).
In real life, it is not beverages, I guess. The beverage is one & flavors added on top of it.

The purpose of decorator is - to decorate. .Net has TextWriter and IndentedTextWriter (I guess), which basically takes the normal text of yours and applies indentation to it. It is similar to unix pipes in a way, if you think of it.

input -> tweaks -> tweaked input -> further tweaks -> further tweaked input.
Output of current operation becomes input for next operation.

I don't know if I explained it well.

shahkalpesh
Thanks. This explains it well.
Appu
You explained it well.
Repo Man
+6  A: 

The whole point of the Decorator pattern is to add responsibilities via object composition, not inheritance. Inheritance is static, obj. composition is dynamic and more flexible. The possibilities for decoration are endless. It's also possible to un-decorate an object during runtime.

Can you give more idea about un-decorating?
Appu
+1  A: 

I think that you are actually representing something completely different.

In your example you have an object call order that receives beverages, and in the Head first example they are just decorating a beverage with toppings, this causes the following main problem.

In your order code, you can place more than one beverage, if so, and you place more than one topping, what topping goes with each beverage?

Alberto Gutierrez