DEV Community

Coder
Coder

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

3

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.

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay