Reputation: 99
I am reading the Head First Design Patterns book. In Chapter 3 ("Decorating Objects: The Decorator Pattern"), I do not understand this part:
"Wouldn’t it be easy for some client of a beverage to end up with a decorator that isn’t the outermost decorator? Like if I had a DarkRoast with Mocha, Soy, and Whip, it would be easy to write code that somehow ended up with a reference to Soy instead of Whip, which means it would not include Whip in the order."
Could someone please help me understand the main point of this section, and what the main issue was that the authors were addressing?
Upvotes: 2
Views: 325
Reputation: 382
I think what they wanted to point out, is the fact that you can get your references mixed up if you are not careful where and how you create your decorated objects. Consider the example on page 98 (first edition from 2004).
Beverage beverage3 = new HouseBlend();
beverage3 = new Soy(beverage3);
beverage3 = new Mocha(beverage3);
beverage3 = new Whip(beverage3);
If you would do stuff in between those steps of creation, you might end up with a Mocha without Whip.
And like they wrote in the answer section:
However, decorators are typically created by using other patterns like Factory and Builder.
If you automate your object creation, it might prevent you from making reference errors.
Upvotes: 3