- Decorator Pattern Introduction
- Decorator Starbuzz Code
Head First Design Patterns is the title of a good book that can be used to learn design patterns. This post is based on that books as well as a YouTube video by Christopher that describes the decorator pattern. The C# code is in the second post in this series. the link is just over to the right of this page.
The decorator pattern adds logic to an object without actually opening up that object and changing that object. In the book, they use the example of a coffee shop, Starbuzz. You order a coffee that you need to “doctor up”. You might want to add cream, sugar, steamed milk, mocha, cinnamon, whip cream, caramel syrup, a shot of vanilla, and so on. This coffee that you have might be drip dark roast, drip medium roast, drip mild roast, a single expresso shot or a double-espresso shot, and so on. As you can see the combinations get out of control so that you can end up with a class explosion. If you could doctor up with only 4 different toppings, and you could use each topping either zero or one time, how many different combinations of toppings could you have? If you count the “no toppings” option, the answer is 16. Having four toppings results in 16 different possibilities. 5 toppings results in 32 possibilities. 6 toppings results in 64 possibilities. Have a look at Pascal’s triangle to discover the number pattern. The formula is 2 to the exponent of the number of toppings. All of this does not take into account the fact that you could have two shots of vanilla, not just zero or one. We need a pattern to easily deal with all of these combinations.
Another use case would be a hamburger. The “Dummies” book uses that example. You have a hamburger that you could add cheese to make a cheeseburger. You could also add bacon to make it a bacon cheeseburger. And so on.