Design Pattern, Software Development

The Decorator Design Pattern In Simple Words

The Decorator design pattern is an alternative to subclassing that makes our codes flexible and maintainable. Furthermore, it allows us to wrap around existing objects and dynamically modify their behaviors (methods).

When To Use This Pattern?

When do we use the Decorator design pattern? We can use this pattern whenever we want to create subclasses. It is a better alternative to using the extend (or equivalent) keyword, which usually leads to hard-to-maintain codes.

The Decorator Pattern Off The Gang of Four

What does the Gang of Four tell about the Decorator design pattern?

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

For example, consider the following scenario to explain the Decorator pattern. When we decorate object A, another object B has a dependency on it, e.g., parameter to the constructor. Then, object B can override calls to object A‘s methods by running object B‘s methods instead. Also, object B can augment object A‘s methods by deriving new values from their methods’ return values. Therefore, in this case, object A decorates object B.

To decorate object B, another object C has a dependency on it and overrides or augments its methods. So on and so forth.

Other Design Patterns

The Decorator design pattern is only one of the structural design patterns we can use to create maintainable software applications. Check out the other design patterns on Design Patterns Are The Ultimate Toolkit For Programmers.

Loading

Got comments or suggestions? We disabled the comments on this site to fight off spammers, but you can still contact us via our Facebook page!.


You Might Also Like