DEV Community

Coder
Coder

Posted on • Originally published at itscoderslife.wordpress.com on

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 implemented 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 a 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.

Top comments (0)