Thursday, September 2, 2010

Decorator Pattern

Current project we are working on, they heavily used design patterns in their codebase and when it comes to do the modifications and new enhancements, we must have a good understanding on how the design patterns behave and how we can apply in a real world situation to make it more maintainable and optimizable codebase.

Therefore recently I started to do some research on this and got a clear understanding on the Decorator design pattern initially.This pattern is quite useful when you need to extend an object’s behavior dynamically. This ability to dynamically attach new behavior to objects is done by a Decorator class that wraps itself around the original class.

Following example illustrates the usage of the Decorator pattern and the way I illustrated the example was bit funny and it was an incident recently I experienced.

Let’s take a real world entity called Girl for this example. Every girl has a unique feature Smile. So we can create an interface for the Girl, that specifying we need to implement the Smile:


Now we can create an Office girl (concrete class) using the Girl interface and implement the Smile for the Office girl.


Following creates an instance from OfficeGirl and check the Smile:


The output would be:


Now let’s say there is another office girl who wanted Smile and at the same time she needs to do something else too. Let's say for an example flirting. How she can achieve this?

Now the Decorator pattern is coming to the picture. By using it, we can decorate this office girl to do the flirting thingy at the run time!

Following is how we can achieve this using a Decorator class:


Following creates an instance from OfficeGirl and decorate it via OfficeGirlDecorator and check the Smile:


The output would be:


In this example if you look at the Decorator class, it can invoke just like the original class. In most cases, method calls are delegated to the original class and then the results are acted upon, or decorated, with additional functionality.

Still not got it? For more information visit Gang of Four, Wikipedia

4 comments:

Himesha said...

Nicely presented!

Anonymous said...

Nicely explained machan...!!!!

But tell me are you still trying to hit it up with that NSB girl who's traveling in the same bus/route with you....???? LOL

Anonymous said...

that too will pass.. ;)

Hisny said...

Nicely done Janaka. Very much understandable :)