Wednesday 1 February 2012

Decorator Pattern



The decorator pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.


From what I have learnt from my ventures through software development is that developers are often faced with scenarios where they have to adapt, or add extra functionality to an existing application.

Now an important design principle for OOP is that Classes should be open for extension, but closed for modification.

This means that the internal logic of an existing class shouldn’t have to be changed if additional functionality needs to be added. However one should be able to extend the functionality using Decorators.

We often see the use of “Decorating” within API’s where a defined set of classes are initiated. The programmer using the API doesn’t have access to directly alter the logic of these classes however they have the ability to extend the functionality using Decorators. Such as the stream classes within the java API


I will demonstrate how the decorator pattern is implemented with an example similar to MTV’S pimp my ride    ; )

In this example the main component will be the car that will be “pimped” and the decorators will represent the additional car parts.



 
The diagram shows the base class Car which acts as the component class; the three concrete components represent our cars to be “pimped”: SUV, Coupe and Old school. The abstract class CarParts that inherit the base class Car is used by the decorators: BodyKit, Exhaust, Spoiler and Brakes to add functionality to the derived Car classes. 

Code






































































































Results


















Latter I will do a brief analysis of each pattern and highlight their advantages and disadvantages... Please stay tuned.........

1 comment: