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:https://www.jiyik.com/en/xwzj/algorithm_9859.html

Related Articles

How to find the IP address of the local host in Java

Publish Date:2025/03/17 Views:98 Category:NETWORK

The Java Networking API provides a way to find the local host IP address from a Java program using the java.net InetAddress class. It is rare that you need the local host IP address in a Java program. Most of the time, I use the Unix command to find t

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:58 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Do you understand JavaScript closures?

Publish Date:2025/02/21 Views:111 Category:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

Publish Date:2025/02/21 Views:183 Category:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

Publish Date:2025/02/21 Views:156 Category:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

Scan to Read All Tech Tutorials

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

Recommended

Tags

Scan the Code
Easier Access Tutorial