Decorator Design Pattern in Java

By | July 4, 2020

In this post, We will talk and learn about the Decorator Design Pattern in Java.

  • Decorator design pattern comes under structural design patterns.
  • Decorator design pattern is used to modify the functionality of an object at runtime. At the same time, other instances of the same class will not be affected by this, so individual object gets the modified behavior.
  • This Pattern provides a wrapper to the existing class.
  • Decorator design pattern uses abstract classes or interfaces with the composition to implement the wrapper.
  • The decorator design pattern is helpful in providing runtime modification abilities and hence more flexible. It’s easy to maintain and extend when the number of choices are more.

Decorator Design Pattern in JDK:

  • Decorator pattern is used a lot in Java IO packages, such as FileReader, BufferedReader, BufferedInputStream  etc.
  • java.util.Collections ( synchronizedXXX() and unmodifiableXXX() methods)
  • javax.servlet.http.HttpServletRequestWrapperand HttpServletResponseWrapper

Below is the complete source code:

Decorator Design Pattern project

Bike.java

BasicBike.java

LuxuryBike.java

SportsBike.java 

 DecoratorBike.java

 ClientTest.java

Output of this client Program:

———–Assemble Basic Bike————-
Basic Bike..
———–Decorate BasicBike with Luxury Feature————
Basic Bike..
Adding featues of Luxury Bike..
——Decorate BasicBike with Luxury and Sports Features—–
Basic Bike..
Adding featues of Luxury Bike..
Adding featues of Sports Bike..

 

You May Also Like:

Singleton Design Pattern in java
Prototype Pattern in Java
Factory Pattern in Java
Abstract Factory Pattern in Java
Builder Pattern in Java
Adapter Design Pattern in Java

That’s all about the Decorator Design Pattern in Java.
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published.