Monday, June 2, 2014

Head First C++ code for StarbuzzCoffee : A Decorator Pattern

The third chapter in the Head First Design Patterns book explains another fundamental design principle that forms the basis of Decorator design pattern. The fourth design principle can be summed as

"Classes should be open for extension, but closed for modification."

The example code in Chapter 3 the Decorator Pattern provide Java Implementation of StarBuzzCoffee billing application. I tried to write similar code in C++ that explains the Decorator Pattern used in the program.
Inheriting from Base class that implements a lot of methods is not a good idea, as some of sub-classes might not need all the functionality (methods) of Base class. Also it violates design principle 2 explained in previous post.
Inheriting behavior by sub classing, set the behavior statically at compile time. And all sub-classes must inherit the same behavior. If object's behavior is extended through composition (has-a), then it can be extended dynamically at a runtime.
It is possible to add multiple new responsibilities to objects through this technique (composition), including responsibilities that were not even thought of by the designer of the superclass. And we don't have to touch their code! By dynamically composing objects, new functionality can be added by writing new code than altering existing code. This reduces chances of introducing Bugs.

Decorator pattern provides an alternative to sub-classing for extending behavior, it attaches additional responsibilities to an object dynamically. Decorators need the same "interface" as the component they wrap because they need to stand up in place of the component.
In the example code we subclass the abstract class Beverage in order to have correct type, not to inherit its behavior. The behavior is acquired by composing objects together. Decorators change the behavior of their components by adding new functionality that they achieve by wrapping the component of same type ( Since Decorator extends the same Base class as components they wrap).
Here CondimentDecorator class provides decorator interface that will wrap the objects of type Beverage ( Sub-classed from), that is why Condiment inherit from same abstract class Beverage, but it inherits from Beverage to get type so that it can wrap beverages. The behavior will be extended by composition dynamically as CondimentDecorator store reference to Beverage.

Here is the class diagram of StarBuzzCoffee




















The c++ code is build using VS2010 IDE. You can download code from here.

No comments: