Hi everyone! Chapter three inHead First Design Patterns: A Brain-Friendly Guideintroduces us to the Decorator pattern. A pattern that is heavily used in the JDK’s java.io package. And although not perfect, it can be combined with Factory and Builder pattern (not yet covered) to make them more useful and clean. Let’s talk about the Decorator pattern.
A new design principle is introduced in this chapter. Classes should be open for extension, but closed for modification.And it helps us understand that inheritance is only one form of extension, but not necessarily the best way to achieve flexibility in our designs.The pattern favors composition and delegation to add new behaviors during runtime, rather than during compile-time. In our designs we should allow behavior to be extended without the need to modify existing code. Lets give this pattern a formal definition.
Decorator Pattern:This pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.
This definition doesn’t really tell us how this pattern is implemented, so lets take a look at a class diagram definition. I wont reproduce the class diagram in the text, I’ll give another slightly different diagram. In the diagram below ‘Component’ is an interface instead of an abstract class, but the general idea is still the same.
Now let me give a concrete example thats a little different from the text. Lets say we are starting our own taco stand restaurant, and we need to write some code for our taco stand’s ordering system. And lets say our starting point is a ‘Taco’ interface.
There are four types of tacos we want to serve: beef, chicken, pork, and veggie. Then there are four condiments we can add to a taco: cilantro, onion, avocado, and potato (we don’t put lettuce or tomato on our tacos). Now lets show a class diagram four our taco stand’s ordering system that implements the decorator patten design.
And now lets take a look at some actual code implementing this design. First the Taco interface(component).
Next some Taco implementations (concrete components).
Next lets look at the Condiment Decorator (Decorator).
Now some condiment implementations (concrete decorators).
The Decorator Pattern involves a set of decorator classes(cilantro, onion, avocado, potato) that are used to wrap concrete components (beef, chicken, pork, veggie). So lets take a look at some code that glues this all together. Note that we will learn about much better ways of creating decorated objects when we cover the Factory and Builder design patterns.
Good news. I checked in all this code and verified it works as expected. If you are curious you can check it out on GitHub here.
That is it! That is the Decorator pattern in action, thanks for reading