JIYIK CN >

Current Location:Home > Learning > ALGORITHM >

Java Decorator Design Pattern Example

Author:JIYIK Last Updated:2025/03/19 Views:

Hello everyone, if you want to learn about Decorator Design Pattern in Java , then you have come to the right place. As design patterns are very important while building software and equally important in any core Java interview, it is always good to have a clear understanding of various design patterns in Java. In this article, we will explore and learn about Decorator Design Pattern in Java , which is a prominent Java core design pattern and we can see many examples of it in JDK itself.

JDK uses decorator pattern in IO package, which decorates Reader and Writer classes for various scenarios, such as BufferedReaderand BufferedWriterare examples of decorator design pattern in Java.

From setting up a class or interface in Java. Now let's move on to the decorator pattern in Java .

By the way, to best understand design patterns, we need to work out some scenarios, examples, etc.


Decorator Design Pattern in Java

In this article, we will see:

  • What is the Decorator pattern in Java?
  • When to use decorator pattern in Java?
  • How to use the decorator pattern in Java?
  • Decorator Design Pattern Example
  • Advantages and Disadvantages of Decorator Pattern in Java

What is the Decorator Design Pattern in Java?

  • The Decorator design pattern is used to enhance the functionality of a particular object at runtime or dynamically.
  • At the same time, other instances of the same class are not affected by this, so a single object gets the new behavior.
  • Basically we wrap the original object by a decorator object.
  • The decorator design pattern is based on an abstract class from which we derive concrete implementations.
  • It is a structural design pattern and is the most widely used.

What problem does the decorator design pattern solve?

Now the question is why this pattern came about and what problem does the existing system have to solve? So the answer is that if someone wants to add some functionality to a single object or change the state of a particular object at runtime, it is not possible.

It is possible that we can provide a specific behavior to all the objects of that class at design time with the help of inheritance or using subclassing, but the decorator pattern allows us to provide a specific behavior or state to a single object of the same class at runtime. This will not affect other objects of the same class in Java.

When to use the decorator pattern in Java

When subclassing becomes impractical, we need a large number of different possibilities to make independent objects, or we can say we have a combinatorial number of objects.

Secondly, we use the decorator design pattern when we want to add functionality to a single object instead of all objects at runtime.

Code example of the decorator design pattern:

To better understand the concept of decorator design pattern, let's look at a code example of using decorator pattern in Java. We can also look inside JDK and find classes and packages that use decorator pattern.

public abstract class Currency {
    String description = "Unknown currency";

    public String getCurrencyDescription() {
        return description;
    }

    public abstract double cost(double value);

}


// Concrete Component

public class Rupee extends Currency {
    double value;

    public Rupee() {
        description = "indian rupees";
    }

    public double cost(double v) {
        value = v;
        return value;
    }

}

//Another Concrete Component

public class Dollar extends Currency {
    double value;

    public Dollar() {
        description = "Dollar”;
    }

    public double cost(double v) {
        value = v;

        return value;

    }

}

// Decorator

public abstract class Decorator extends Currency {

    public abstract String getDescription();

}


// Concrete Decorator

public class USDDecorator extends Decorator {

    Currency currency;


    public USDDecorator(Currency currency) {
        this.currency = currency;
    }


    public String getDescription() {
        return currency.getDescription() + " ,its US Dollar";
    }


}


//Another Concrete Decorator

public class SGDDecorator extends Decorator {
    Currency currency;

    public SGDDecorator(Currency currency) {
        this.currency = currency;
    }


    public String getDescription() {
        return currency.getDescription() + " ,its singapore Dollar";
    }

}


public class CurrencyCheck {

    public static void main(String[] args) {

        // without adding decorators

        Currency curr = new Dollar();

        System.out.println(curr.getDescription() + " dollar. " + curr.cost(2.0));


        //adding decorators

        Currency curr2 = new USDDecorator(new Dollar());

        System.out.println(curr2.getDescription() + " dollar. " + curr2.cost(4.0));

        Currency curr3 = new SGDDecorator(new Dollar());

        System.out.println(curr3.getDescription() + " dollar. " + curr3.cost(4.0));
    }
}

Code Explanation:

We can understand this in the following terms:

  1. Component interface : In our example, the currency interface is a standalone component or we need a decorator.

  2. Concrete Component : It implements the component and we dynamically add new behaviors to this object. Dollar and Rupee are concrete implementations of Currency.

  3. Decorator : Decorator contains a HAS simple relationship, we can say that it has an instance variable which holds a reference to the component that implements the same component they are going to decorate. Here Decorator is an abstract class which extends Currency.

  4. Concrete Decorator : It is an implementation of Decorator so USD Dollar and SGD Dollar are implementations of Decorator which contain instance variables of component interface or the thing they are decorating.

Here is a nice UML diagram:

Decorator pattern UML diagram

Advantages of Decorator Design Pattern in Java

In short, we saw what are the main advantages of using the decorator design pattern.

  1. Decorator Pattern is more flexible than inheritance because inheritance adds responsibility at compile time and will be added at runtime.
  2. The decorator pattern enhances or modifies the functionality of an object

Disadvantages of the Decorator Pattern

The main disadvantage of using the decorator pattern in Java is that code maintenance can be a problem because it provides a lot of similar small objects (each decorator).

That's all about the Decorator design pattern in Java. To master the Decorator pattern, I suggest looking at the JDK library itself and finding out which classes are decorated and why they are decorated. Also, think of a scenario where inheritance is not practical and you look more flexible and try to use the Decorator pattern in Java there.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

Store Div Id in PHP variable and pass it to JavaScript

Publish Date:2025/04/13 Views:51 Category:PHP

This article shows you how to div id store a in a PHP variable and pass it to JavaScript code. We will answer the following questions. What is div id ? How to div id store in a PHP variable? How to pass variables to JavaScript code? Let’s

Design Patterns in Java - Visitor Pattern

Publish Date:2025/03/19 Views:175 Category:ALGORITHM

Today, we are going to learn one of the most useful patterns, the Visitor Pattern. What is the Visitor pattern? Well, let's look at an example. Let's say you're a software engineer working at a university. The university rarely has establis

How to use Strategy Pattern in Java?

Publish Date:2025/03/19 Views:142 Category:ALGORITHM

Hi everyone, you might have heard, “Can you tell me about any design pattern other than Singleton design pattern that you have used recently in your project?”. This is one of the popular questions in various Java interviews in recent ye

Difference between Proxy Mode and State Mode in Java

Publish Date:2025/03/19 Views:76 Category:ALGORITHM

Hi guys, if you are preparing for Java interview and looking for difference between Proxy and State design pattern, then you are at the right place. In the past, I have explained several important object-oriented design patterns like State,

Strategy Design Pattern and Open-Closed Principle in Java

Publish Date:2025/03/19 Views:114 Category:ALGORITHM

The Strategy design pattern is based on the Open/Closed design principle , the famous " O SOLID " of design principles . It is one of the patterns that has become popular in the field of object-oriented analysis and design, along with the D

How to implement binary search in Java without recursion?

Publish Date:2025/03/19 Views:198 Category:ALGORITHM

Hey Java programmers, if you want to implement binary search in Java and looking for iterative and recursive binary search algorithms, then you have come to the right place. Today I am going to teach you an important algorithm. In computer

How to implement the singleton pattern in JavaScript ES6+

Publish Date:2025/03/19 Views:55 Category:ALGORITHM

In this article, we will show you how to implement the singleton pattern in JavaScript. If we are a full-stack JavaScript developer, we know that JavaScript is a powerful language and we can build amazing websites with it. On the other hand

How to use the Adapter design pattern in Java

Publish Date:2025/03/19 Views:77 Category:ALGORITHM

The Adapter design pattern in Java , also known as the Wrapper pattern, is another very useful GOF pattern that helps bridge the gap between two classes in Java. According to the Gang of Four pattern list, Adapter is a structural pattern, m

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial