The decorator design pattern is one of the classic design patterns used to overcome the recurring design problems in object-oriented software. It allows us to add functionality to an object dynamically. By dynamically, we mean modifying the behaviour of an object at run time.

Although we have used the term behaviour, but decorator design pattern falls in the category of structural design pattern, because it has something to do with the way we structure our classes.

There are a few bumpy areas in using inheritance to which the decorator design pattern provides an elegant solution.

Decorator design pattern in java with examples

This article will first describe what decorator design pattern is, why to use it and then we will use a simple decorator design pattern java example to demonstrate its significance.

What is decorator design pattern in java?

Decorator design pattern in java proposes a way to customise our objects dynamically during run time, instead of us having to write code to do that during compile time.

You can think of it as an alternative to sub classing. When we subclass a parent class, there might be multiple combination of classes resulting in a class explosion.

As you can see in the image below, the beverage class is being subclassed by multiple classes to add their own blend to it. Although it seems to follow the Single Responsibility Principle, it quite does not seem an elegant solution and obviously is hard to maintain.

#programming #coding #design-patterns #technology #java

What is Decorator design pattern in Java?
1.50 GEEK