OOP Design Patterns 3— Decorator Pattern

Dinesha Karunathilake
2 min readNov 28, 2020

When in a software project, need comes to extend the behavior of the product by adding new functionalities, we could use inheritance by subclassing to extend the behavior of an object. But then inheritance is done at compile-time and methods are also available for other instances of that class. Because of the code modification, there is a violation of the Open-Closed Principle. To avoid this violation of the SOLID principle, we can attach new responsibility to an object dynamically by using composition over inheritance at design time, which makes it flexible.

The decorator pattern uses this approach to solve the inheritance problem.

Definition:

The decorator pattern attaches additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

Following is the UML diagram of the Decorator Pattern and it also explains the pattern.

  • The Decorator Pattern involves a set of decorator classes that are used to wrap concrete components.
  • Decorator classes mirror the type of the components they decorate. (In fact, they are the same type as the components they decorate, either through inheritance or interface implementation.)
  • Decorators change the behavior of their components by adding new functionality before and/or after (or even in place of) method calls to the component.
  • You can wrap a component with any number of decorators. Decorators are typically transparent to the client of the component; that is unless the client is relying on the component’s concrete type.
  • Decorators can result in many small objects in our design, and overuse can be complex.

Check how the Decorator Pattern was used to solve the problem of combining different types of workouts together to calculate total calorie burn.

https://github.com/DineshaKarunathilake/DesignPatterns/tree/master/decorator

--

--