Decorator design pattern [Structural]

The Decorator Design Pattern allows adding new behavior to existing types. We can extend the functionality of the type without modifying its implementation which is a flexible alternative to subclassing.

The Decorator can be implement via wrapping the object to be enhanced. Extensions provide the ability to add additional methods to types without having to suppress or change their source code.

The Decorator Design Pattern adds new responsibilities to objects without modifying the code of the type used to create them

Example:

A Basic Color class lets you create color with RGB and HSB. What if I have to create color using hex values? Typically we subclass. Instead of subclassing we need to extend the same color class and add a function to create color with hex values.

Another example would be when ordering food online a typical burger or subway sandwich would cost x then user also has options to add extra cheese or steak. Sometimes the vendor provides option to add a drink to the cart. All this adding extras would cost additional charges. The final cost is caluclated with calling the decorators to add their cost to the cart over the base item.

Common misuses: Accidentally replacing the existing functionality of a type. Another misuse is that we may change the original purpose of a type by decorating it with unrelated behavior.

 

 

Advertisements

One thought on “Decorator design pattern [Structural]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s