Java Structural Design Patterns – Decorator Pattern

The Decorator Pattern comes under the Structural pattern. By using the decorator pattern we can modify the functionality of an object dynamically. The functionality of an object is extended by adding additional coverage around an object. If a number of objects are present for a single class, we can modify the behavior of a single object without affecting the other instances of the same class.

If your solution or project has below points you can consider using Decorator Pattern:

  • The responsibilities need to be added or removed dynamically from an object.
  • A flexible framework is required to subclass or extending functionality.

The pattern can be designed so that multiple decorators can be stacked on top of each other, each time adding a new functionality.

Decorator Pattern by Example

We will understand this patter using simple concept of a Flat. At first, there will be a simple flat with one bedroom, hall, and kitchen. Later we will go on and different features to this basic flat.

Flat (Component): It is an interface which creates a blueprint for the class which will have decorators.
SimpleFlat (Concrete Component): Object for a simple flat of 1 bedroom, hall and kitchen. Extra functionality will be attached to it dynamically.
FlatDecorator(Abstract Decorator): Decorator object for SimpleFlat object. Extra functionality will be attached to it dynamically but other decorators.

Similarly, we have decorators to add facilities like modular kitchen, garden etc.

Let us see the code.

Flat.java

SimpleFlat.java

Adding Furnishing Feature

Adding Kitchen Feature

Running the Example

Output

Conclusion

By using this pattern additional responsibilities are given to individual objects dynamically without affecting other objects of the same class. In short, this pattern is very flexible but at the same time code maintenance is difficult because lots of decorators we can create by using this pattern which is difficult to maintain and differentiate.

The source code is available in our Github repository.

Download Code

 

2 Comments
  1. c
    June 22, 2018 | Reply
    • Pavan
      June 22, 2018 | Reply

Add a Comment

Your email address will not be published. Required fields are marked *