Skip to main content

Decorator design pattern

Greetings!

Decorator is a structural design pattern.

When we need to add extra functionality to an object it is normal to do it through inheritance. Depending on the number of functionalities we may end up higher number of class hierarchy which leads to maintenance nightmare.

Using Decorators we can add additional responsibilities using composition at run time. We do not have to modify existing class but we can "decorate" it to add extra functionalities.

Inheritance is one form of extension, but not necessarily the best way to achieve flexibility in our designs.

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


Image source wikipedia

Let's see a sample,

  • Classes should be open for extension but closed for modification.

Comments