DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Design Pattern: What You Need to Know to Improve Your Code Effectively
  • Prototype Pattern in JavaScript
  • Object Relational Behavioral Design Patterns in Java
  • Distribution Design Patterns in Java - Data Transfer Object (DTO) And Remote Facade Design Patterns

Trending

  • Enhancing Security With ZTNA in Hybrid and Multi-Cloud Deployments
  • Fixing Common Oracle Database Problems
  • Stateless vs Stateful Stream Processing With Kafka Streams and Apache Flink
  • Performance Optimization Techniques for Snowflake on AWS
  1. DZone
  2. Coding
  3. Languages
  4. Gang of Four – Decorate with Decorator Design Pattern

Gang of Four – Decorate with Decorator Design Pattern

By 
Mainak Goswami user avatar
Mainak Goswami
·
Dec. 16, 12 · Interview
Likes (1)
Comment
Save
Tweet
Share
37.4K Views

Join the DZone community and get the full member experience.

Join For Free

 Decorator pattern is one of the widely used structural patterns. This pattern dynamically changes the functionality of an object at runtime without impacting the existing functionality of the objects. In short this pattern adds additional functionalities to the object by wrapping it.

Problem statement:

Imagine a scenario where we have a pizza which is already baked with tomato and cheese. After that you just recall that you need to put some additional topping at customer’s choice. So you will need to give some additional toppings like chicken and pepper on the go.

Intent:

Add or remove additional functionalities or responsibilities from the object dynamically without impacting the original object.
At times it is required when addition of functionalities is not possible by subclassing as it might create loads of subclasses.

Solution:

So in this case we are not using inheritance to add additional functionalities to the object i.e. pizza, instead we are using composition. This pattern is useful when we don’t want to use inheritance and rather use composition.

 Structure

Decorator Design Pattern

Decorator Design Pattern Structure

Following are the participants of the Decorator Design pattern:
Component – this is the wrapper which can have additional responsibilities associated with it at runtime.
Concrete component- is the original object to which the additional functionalities are added.
Decorator-this is an abstract class which contains a reference to the component object and also implements the component interface.
Concrete decorator-they extend the decorator and builds additional functionality on top of the Component class.

Example:

Decorator Design Pattern Example

Decorator Design Pattern Example

In the above example the Pizza class acts as the Component and BasicPizza is the concrete component which needs to be decorated. The PizzaDecorator acts as a Decorator abstract class which contains a reference to the Pizza  class. The ChickenTikkaPizza is the ConcreteDecorator which builds additional functionality to the Pizza class.

Let’s summarize the steps to implement the decorator design pattern:

  1. Create an interface to the BasicPizza(Concrete Component) that we want to decorate.
  2. Create an abstract class PizzaDecorator that contains reference field of Pizza(decorated) interface.
  3. Note: The decorator(PizzaDecorator) must extend same decorated(Pizza) interface.
  4. We will need to now pass the Pizza object that you want to decorate in the constructor of decorator.
  5. Let us create Concrete Decorator(ChickenTikkaPizza) which should provide additional functionalities of additional topping.
  6. The Concrete Decorator(ChickenTikkaPizza) should extend the PizzaDecorator abstract class.
  7. Redirect methods of decorator (bakePizza()) to decorated class’s core implementation.
  8. Override methods(bakePizza()) where you need to change behavior e.g. addition of the Chicken Tikka topping.
  9. Let the client class create the Component type (Pizza) object by creating a Concrete Decorator(ChickenTikkaPizza) with help from Concrete Component(BasicPizza).
  10. To remember in short : New Component = Concrete Component + Concrete Decorator

Pizza pizza = new ChickenTikkaPizza(new BasicPizza());

Code Example:

BasicPizza.java

public String bakePizza() {
        return "Basic Pizza";
    }

Pizza.java

public interface Pizza {
    public String bakePizza();
}

PizzaDecorator.java

public abstract class PizzaDecorator implements Pizza {
    Pizza pizza;
    public PizzaDecorator(Pizza newPizza) {
        this.pizza = newPizza;
    }
    @Override
    public String bakePizza() {
        return pizza.bakePizza();
    }
}

ChickenTikkaPizza.java

public class ChickenTikkaPizza extends PizzaDecorator {
    public ChickenTikkaPizza(Pizza newPizza) {
        super(newPizza);
    }
    public String bakePizza() {
        return pizza.bakePizza() + " with Chicken topping added";
    }
}

Client.java

public static void main(String[] args) {
        Pizza pizza = new ChickenTikkaPizza(new BasicPizza());
        System.out.println(pizza.bakePizza());
 
    }

Benefits:

Decorator design pattern provide more flexibility than the standard inheritance. Inheritance also extends the parent class responsibility but in a static manner. However decorator allows doing this in dynamic fashion.

Drawback:

Code debugging might be difficult since this pattern adds functionality at runtime.

Interesting points:

  • Adapter pattern plugs different interfaces together whereas decorator pattern enhances the functionality of the object.
  • Unlike Decorator Pattern the Strategy pattern changes the original object without wrapping it.
  • While Proxy pattern controls access to the object the decorator pattern enhances the functionality of the object.
  • Both Composite and Decorator pattern uses the same tree structure but there are subtle differences between both of them. We can use composite pattern when we need to keep the group of objects having similar behavior inside another object. However decorator pattern is used when we need to modify the functionality of the object at runtime.
  • There are various live examples of decorator pattern in Java API.
    1. java.io.BufferedReader;
    1. java.io.FileReader;
    1. java.io.Reader;

If we see the constructor of the BufferedReader then we can see that the BufferedReader wraps the Reader class by adding more features e.g. readLine() which is not present in the reader class.
We can use the same format like the above example on how the client uses the decorator pattern new BufferedReader(new FileReader(new File(“File1.txt”)));
Similarly the BufferedInputStream is a decorator for the decorated object FileInputStream.
BufferedInputStream bs = new BufferedInputStream(new FileInputStream(new File(“File1.txt”)));

Anyways I hope my readers have liked this article. Please do not hesitate to provide your valuable feedback and comments.

Design Decorator pattern Object (computer science)

Published at DZone with permission of Mainak Goswami, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Design Pattern: What You Need to Know to Improve Your Code Effectively
  • Prototype Pattern in JavaScript
  • Object Relational Behavioral Design Patterns in Java
  • Distribution Design Patterns in Java - Data Transfer Object (DTO) And Remote Facade Design Patterns

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!