00:00

Decorator Design Pattern in Java

Last updated:

The decorator design pattern in Java adds behaviour to an object by wrapping it in another object that has the same interface. Each wrapper does its own small job, such as adding a fee, compressing data or writing an audit log, and then passes the call to the object inside, so features can be stacked in any combination at runtime.

It matters because inheritance does not scale when features combine. Logging, masking and retries for both email and SMS would need a subclass for every mix. Decorators replace that tree of subclasses with small, reusable layers. Decorator is a structural design pattern, and you already use it every time you write new BufferedReader(new InputStreamReader(...)).

1. What Is the Decorator Design Pattern?

The GoF intent is: "Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality."

The idea rests on two facts about every decorator: it is a component (it implements the same interface), and it has a component (it holds a reference to the object it wraps). Because of the first fact, a decorated object can be used anywhere the plain one could. Because of the second, decorators can wrap other decorators, forming a chain.

When a method is called on the outermost layer, it does its extra work before and/or after forwarding the call inward, until the call reaches the original object. Adding a feature means writing one new decorator class, not touching existing ones, which is the Open/Closed Principle in action. Each decorator also has one reason to change, which keeps it aligned with the Single Responsibility Principle.

2. Key Components

ComponentResponsibilityIn the Basic Example
ComponentThe interface shared by the real object and all decoratorsPurchase
Concrete ComponentThe original object that does the core workBaseOrder
Base DecoratorHolds the wrapped component and forwards every call by defaultPurchaseDecorator
Concrete DecoratorsOverride selected methods to add behaviourGiftWrap, ExpressDelivery, Insurance

The client builds the chain once, holding only the outermost object as a Purchase. Each call travels inward through the layers to BaseOrder, and each layer adjusts the result on the way back out.

3. When Is Decorator Useful?

  • Optional add-ons: an order with any mix of gift wrap, express delivery and insurance.
  • Layered data processing: reading a file that is compressed, buffered and decoded, one concern per layer.
  • Cross-cutting policies: fraud screening, idempotency and auditing around a payment gateway, switched on per environment.

4. UML Class Diagram

The diagram shows the Basic Example.

Decorator UML class diagram BaseOrder and the abstract PurchaseDecorator implement the Purchase interface. PurchaseDecorator holds one Purchase, which it wraps. GiftWrap, ExpressDelivery and Insurance extend PurchaseDecorator. «interface» Purchase + cost(): BigDecimal + description(): String implements BaseOrder - cartTotal: BigDecimal + cost(), description() «abstract» PurchaseDecorator # inner: Purchase + cost(), description() wraps 1 extends GiftWrap ExpressDelivery Insurance
Decorator: every decorator is a Purchase and also holds a Purchase, so decorators can wrap the base order or each other.
  1. Purchase is the component interface. BaseOrder and PurchaseDecorator both implement it.
  2. PurchaseDecorator also holds one Purchase (hollow diamond, "wraps"). This is-a plus has-a combination is the heart of the pattern.
  3. The concrete decorators extend the abstract decorator (solid line, hollow triangle) and override only what they change.
  4. Because the wrapped type is the interface, a decorator can wrap a BaseOrder or another decorator.

5. Step-by-Step Execution Flow

Take new Insurance(new ExpressDelivery(new GiftWrap(new BaseOrder("2000.00")))):

  1. The objects are built from the inside out, so Insurance is the outermost layer.
  2. The client calls cost() on Insurance, which first asks its inner object, ExpressDelivery.
  3. ExpressDelivery asks GiftWrap, which asks BaseOrder, which returns 2000.00.
  4. On the way back out, GiftWrap adds 49 (2049.00), and ExpressDelivery adds 99 (2148.00).
  5. Insurance adds 2% of 2148.00 and returns 2190.96.

Wrap the same parts in a different order and the insurance is calculated on a different base, which is why decorator order matters.

6. Real-World Use Cases

  • E-commerce: price add-ons, discounts and taxes applied as layers.
  • Payments and banking: fraud screening, idempotency, auditing and metrics around a gateway client.
  • Notifications: masking sensitive data, adding tracking links, or logging around any sender.
  • The JDK: java.io is built on decorators. BufferedInputStream, DataInputStream and GZIPInputStream extend FilterInputStream and wrap another InputStream. Collections.unmodifiableList() and Collections.synchronizedList() wrap a list with the same interface and add behaviour.
  • Servlet and Spring: HttpServletRequestWrapper is a decorator base class for requests, and Spring's ContentCachingRequestWrapper builds on it to cache the body for logging. In WebFlux, ServerHttpRequestDecorator plays the same role.

7. Problem Without the Pattern

Adding features through inheritance:

NotifierWithoutDecorator.java
public class NotifierWithoutDecorator {

    static class EmailNotifier {
        void send(String to, String message) { System.out.println("  email to " + to + ": " + message); }
    }

    static class SmsNotifier {
        void send(String to, String message) { System.out.println("  sms to " + to + ": " + message); }
    }

    // Each feature combination needs its own subclass
    static class LoggedEmailNotifier extends EmailNotifier {
        @Override
        void send(String to, String message) {
            System.out.println("  [log] sending");
            super.send(to, message);
        }
    }

    static class MaskedLoggedEmailNotifier extends LoggedEmailNotifier {
        @Override
        void send(String to, String message) {
            super.send(to, message.replaceAll("\\d{4}(?=\\d{4})", "****"));   // mask card numbers
        }
    }

    // Same features for SMS? Copy both classes again
    static class LoggedSmsNotifier extends SmsNotifier {
        @Override
        void send(String to, String message) {
            System.out.println("  [log] sending");
            super.send(to, message);
        }
    }

    public static void main(String[] args) {
        new MaskedLoggedEmailNotifier().send("asha@example.com", "Card 41111111 charged");
        new LoggedSmsNotifier().send("+91-98xxxxxx10", "Card 41111111 charged");   // no masking class for SMS yet
    }
}
Console
  [log] sending
  email to asha@example.com: Card ****1111 charged
  [log] sending
  sms to +91-98xxxxxx10: Card 41111111 charged
  • Class explosion: two channels and two features already need four extra classes; each new feature doubles that.
  • Duplication: the logging code appears once per channel.
  • A real gap: SMS has no masking class yet, so the card number leaks.
  • Fixed at compile time: you cannot switch features on or off per customer or environment.

8. Solution Using the Pattern

Give both channels one Notifier interface, then write Logging and Masking as decorators that implement it and wrap any other notifier. Any channel can now get any feature by wrapping: new Logging(new Masking(new SmsNotifier())).

The number of classes grows with the number of features, not with their combinations. Each feature is written once, the SMS leak disappears because masking works for every channel, and the chain can be assembled from configuration at runtime. The examples apply this structure to prices, I/O streams and payments.

9. Decorator Design Pattern in Java: Code Examples

Each example is a single file that runs on Java 21 with java FileName.java.

Basic Example: Order Add-ons

Problem: customers can add gift wrap, express delivery and insurance in any combination, and insurance is a percentage of whatever it covers.

PurchaseDecoratorDemo.java
import java.math.BigDecimal;
import java.math.RoundingMode;

public class PurchaseDecoratorDemo {

    // Component
    interface Purchase {
        BigDecimal cost();
        String description();
    }

    // Concrete component
    static final class BaseOrder implements Purchase {
        private final BigDecimal cartTotal;

        BaseOrder(String cartTotal) { this.cartTotal = new BigDecimal(cartTotal); }

        public BigDecimal cost() { return cartTotal; }
        public String description() { return "Cart"; }
    }

    // Base decorator: holds a Purchase and delegates to it
    abstract static class PurchaseDecorator implements Purchase {
        protected final Purchase inner;

        protected PurchaseDecorator(Purchase inner) { this.inner = inner; }

        public BigDecimal cost() { return inner.cost(); }
        public String description() { return inner.description(); }
    }

    // Concrete decorators
    static final class GiftWrap extends PurchaseDecorator {
        GiftWrap(Purchase inner) { super(inner); }
        @Override public BigDecimal cost() { return inner.cost().add(new BigDecimal("49.00")); }
        @Override public String description() { return inner.description() + " + gift wrap"; }
    }

    static final class ExpressDelivery extends PurchaseDecorator {
        ExpressDelivery(Purchase inner) { super(inner); }
        @Override public BigDecimal cost() { return inner.cost().add(new BigDecimal("99.00")); }
        @Override public String description() { return inner.description() + " + express"; }
    }

    // Insurance costs 2% of whatever it wraps, so its position matters
    static final class Insurance extends PurchaseDecorator {
        Insurance(Purchase inner) { super(inner); }
        @Override public BigDecimal cost() {
            BigDecimal base = inner.cost();
            return base.add(base.multiply(new BigDecimal("0.02")).setScale(2, RoundingMode.HALF_UP));
        }
        @Override public String description() { return inner.description() + " + insurance"; }
    }

    static void print(Purchase p) {
        System.out.println(p.description() + " = Rs. " + p.cost());
    }

    public static void main(String[] args) {
        print(new BaseOrder("2000.00"));
        print(new GiftWrap(new BaseOrder("2000.00")));
        print(new Insurance(new ExpressDelivery(new GiftWrap(new BaseOrder("2000.00")))));
        print(new ExpressDelivery(new GiftWrap(new Insurance(new BaseOrder("2000.00")))));   // same parts, different order
    }
}

Important classes and methods

  • PurchaseDecorator forwards both methods by default, so each concrete decorator overrides only what it changes.
  • inner is final, so a decorator always wraps the same object.
  • Insurance calculates its fee from inner.cost(), so its result depends on its position.

Expected output

Console
Cart = Rs. 2000.00
Cart + gift wrap = Rs. 2049.00
Cart + gift wrap + express + insurance = Rs. 2190.96
Cart + insurance + gift wrap + express = Rs. 2188.00

How it runs

  1. The plain cart costs 2000.00; gift wrap adds 49.
  2. With insurance outermost, it covers wrap and delivery too: 2148.00 + 2% = 2190.96.
  3. With insurance innermost, it covers only the cart: 2040.00 + 49 + 99 = 2188.00.

10. Best Practices and Common Mistakes

Best practices

  • Keep each decorator to one responsibility, and keep the component interface small.
  • Provide a base decorator that forwards everything, so concrete decorators override only what they change.
  • Build chains in one place (a factory, builder or Spring configuration) and document the order.
  • Thread safety: stateless decorators are safe to share. Stateful ones, such as caches, counters and dedup maps, need concurrent collections and atomic operations.

Common mistakes

  • Ignoring order: insurance before or after fees, or auditing inside versus outside fraud checks, changes the result.
  • Forgetting to forward a method, which silently skips the inner layers.
  • instanceof checks on the concrete component, which fail once it is wrapped.
  • Overengineering: using decorators for one fixed feature that a simple method or subclass handles.

11. When to Use and When Not to Use

Use it when features are optional and combine freely, when behaviour must be chosen at runtime, or when you cannot or should not modify the original class.

Avoid it when the interface is large and every decorator must forward dozens of methods, when callers depend on the concrete type, or when a deep stack of wrappers would make stack traces and debugging painful.

12. Advantages and Disadvantages

Advantages

  • Combines features freely without a subclass per combination.
  • Runtime flexibility: chains can come from configuration.
  • Open/Closed: new features are new classes.
  • Small, testable classes with one job each.

Disadvantages

  • Many small objects, and order-dependent behaviour.
  • Identity changes: the outer object is not the original.
  • Harder debugging through several layers.

13. Comparison with Similar Patterns

AspectDecoratorProxyAdapterComposite
IntentAdd responsibilitiesControl accessChange the interfaceTreat groups and single items alike
InterfaceSame as the wrapped objectSame as the subjectDifferent from the adapteeSame for leaves and groups
WrapsOne component, stackableOne subject, usually one layerOne adapteeMany children
Who builds itClient or configurationOften a framework, hidden from the clientIntegration codeThe code that builds the tree

Choose a Decorator to stack optional features, a Proxy to decide whether and when the real object is reached, an Adapter to fix an interface mismatch, and a Composite to treat a tree of objects as one. Strategy is the "inside" alternative: instead of wrapping an object, you swap a part of it.

14. Summary

  • The decorator design pattern in Java wraps an object in layers that share its interface and add behaviour.
  • Purpose: combine optional features without a subclass for every combination.
  • Components: Component, Concrete Component, Base Decorator, Concrete Decorators.
  • Each layer does its work and forwards the call inward; order affects the result.
  • Used in java.io, collection wrappers, servlet request wrappers and payment pipelines.
  • Benefits: runtime composition, Open/Closed design and small focused classes.
  • Document the order, keep stateful decorators thread-safe, and avoid it for huge interfaces.

15. Java Design Pattern Interview Questions and Answers

Q1. The interface you need to decorate has 25 methods. How do you avoid writing 25 forwarding methods in every decorator?

Write the forwarding once in an abstract base decorator, like FilterInputStream does, and let concrete decorators extend it. Alternatives are a JDK dynamic proxy that intercepts only the methods you care about, or Lombok's experimental @Delegate. If many decorators are needed for a huge interface, consider splitting the interface.

Q2. After wrapping a JDBC connection in a decorator, a library's instanceof check fails. How do frameworks solve this?

They expose the wrapped object through an unwrap method. JDBC defines java.sql.Wrapper with isWrapperFor(Class) and unwrap(Class), which connection-pool wrappers implement. Code that needs the vendor class asks for it explicitly instead of using instanceof.

if (connection.isWrapperFor(PGConnection.class)) {
    PGConnection pg = connection.unwrap(PGConnection.class);
}
Q3. How can lambdas implement decorators?

When the component is a functional interface, a decorator is a function that takes one implementation and returns another. Function.andThen() and compose() chain behaviour the same way.

UnaryOperator<PaymentGateway> logging = next -> payment -> {
    System.out.println("charging " + payment.amount());
    return next.charge(payment);
};
PaymentGateway gateway = logging.apply(new ProviderGateway());
Q4. How do you decorate a Spring bean that other beans inject by interface?

Register the original under a qualifier and expose the decorated version as the @Primary bean, so every injection point receives the decorator. For decorating many beans generically, a BeanPostProcessor can wrap them at startup.

@Bean @Qualifier("raw")
PaymentGateway providerGateway() { return new ProviderGateway(); }

@Bean @Primary
PaymentGateway paymentGateway(@Qualifier("raw") PaymentGateway raw) {
    return new Auditing(new Idempotent(raw), auditLog());
}
Q5. Your idempotency decorator works in tests but charges twice in production under load. What is likely wrong?

Probably a non-atomic check-then-act, such as if (!map.containsKey(key)) { charge(); map.put(...); } on a plain HashMap: two threads both see "missing" and both charge. Use ConcurrentHashMap.computeIfAbsent() within one instance. With several service instances, an in-memory map is not enough; store keys in a shared database or cache with a unique constraint.