We have looked at the Factory, the Adapter, and the Singleton patterns. Now we look at the Decorator. The Decorator is similar to the Adapter, but with a subtle difference. With our ReptileAdapter, we wrapped the Reptile class to map the interface methods of Animal to the appropriate methods on Reptile. With the Decorator we also wrap a class, but to add functionality, not to map it or replace the functionality.
The Decorator in the Physical World
The idea behind decorating things in the real world is pretty much how it sounds. We wrap an object with new functionality, while keeping the old functionality. How about a camera in a waterproof housing? When closed up, we have added the functionality of waterproofing, but we still provide a way to press the buttons and turn the dials so that the camera can be operated.
The Decorator in the Software World
On the software side, the idea is the same. It is usually used when we have one object that we like how it functions, but we want to augment the behavior for a different situation. Done correctly, we can keep inserting one object inside another adding functionality at every step.
Continue reading