Structural: Decorator Pattern

-- by Vikram

Extension at runtime rather than at compile time. A decorator is like pre and post hooks, on the objects functionality or say class's functionality. The objective is to supply this decorator and extend the behavior of existing class. You can also understand them as wrappers that have the same super type as that of object that they decorate.

Decorator pattern has at the least one similar objectives as that of bridge pattern, that you are preventing the class explosion. It also aims to help you stick to the open / close principle as defined by the SOLID design principles, which states that a class should be open for extension and closed for modifications. 

There are some characteristics that resemble the adapter and builder patterns, but they have a different objective altogether. What may look similar is that you have implementations that look like adapter but for the same types (sounds weird!), but yes that how we wrap the objects into the objects of the same super-type so that you can incrementally keep on adding the behavioral changes to the objects. 

It can also be said that it is the composition during the runtime. Let's take an example from a car racing game where you have options to modify your car by selecting the speed cards (just like in NFS). In this case your main object is vehicle which defines all the attributes like acceleration, top-speed, brake-response time, cost. If you want to modify all these attributes independently and with all the possible combinations then using a decorator pattern is something that can help you do so rather than trying to extend for each possible combination of speed card usages. In the end you can have code that would look like.

Vehicle v = new Vehicle();v = EnhanceBreaks(v);

//Accepts an object of same type, return an object of same type and hold reference to the original object

v = EnhanceAcceleration(v);

The operations can be performed in any order with any combination. It modifies the behavior or original object by adding some post and pre operations, sometimes decorators can have additional methods, but that doesn't some like something that really gives much advantage because all you ever wanted to use the same original object but with some different behaviors.