Monday, December 13, 2010

Design Patterns - An eye for similarities - Part 3

Decorator Pattern - Wrap me, my brother


The decorator pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to sub-classing for extending functionality.
Typically, the decorator pattern essentially adds a wrapper around a class to add additional capability to it.


This pattern works on the principle of "Open for extension, closed for modification".
So, when we need to add additional capability to the existing object we don't modify the parent class to do that, but make a new class and wrap the existing object in this new class that provides the necessary capability.
For eg. we have a class Mammal and we want to add functionalities to create a Human. We just create a new class HumanDecorator that takes in the Mammal as an object and adds the necessary intelligence into it, thus eliminating the need to change Mammal as a whole. The thing to note here is that both the Mammal and the HumanDecorator class should have the same type. This is done to maintain the extensibility.

Part 4 - Factory Pattern

No comments :