While inheritance is one form of extension it is not always the best way to achieve flexibility in our designs. In certain cases you might want to add a number of different responsibilities to a base class. With the increase in the number of responsibilities you will have to write numerous classes each of them inheriting from the base class. This is where the decorator pattern comes in. It provides an alternative to subclassing. It allows you to add additional responsibilities to an object dynamically.
Let us consider a use case where we have a class called ‘Car’. The maximum speed of any car is 120kmph but by adding some enhancements the speed of the car can be increased to virtually any number(no speed limits imposed). Right now let us assume that there are two such enhancements available in the garage, “Alpha” and “Beta”. “Alpha” and “Beta” can increase the speed of the car by 70kmph and 50kmph respectively. Also we should be able to add n number of these enhancements to reach incredibly high speeds.
While the above implementation looks good enough but imagine what happens when the number of these garage enhancements increase. The combinations of various enhancements would also increase and hence in the end we would end up with a class explosion which would be nothing but a maintenance nightmare.
Now that we know what the pattern is lets write the classes
The base class remains as is
Following the points mentioned above the decorator class will be as follows.
In the same way let’s write our second decorator
Now that our decorators/enhancers are ready let’s create some superfast cars.
That’s it. That’s our hero “The decorator pattern” but use it with caution. Overusing it might end up complicating your design.