SyntaxPilot
Courses/Low-Level Design/Lesson 28
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 28 of 90

Decorator pattern

Decorator patterncomponentconcrete componentdecoratorconcrete decoratorwrappingstacking decoratorsadding responsibilities at runtimejava.io streams as decoratorsCollections.unmodifiableListdecorator vs inheritance

These are the notes for Low-Level Design (LLD) episode 28, the second structural pattern. Last episode the Adapter wrapped an object to change its interface. Today's wrapper keeps the interface exactly the same and adds behaviour: the Decorator. We start at a mall's gift-wrapping counter, then try to bill add-ons at Ramesh's chai stall: one subclass per combination explodes into 8 classes for 3 add-ons and still fails to compile on the 9th order; boolean flags bill "double ginger" at Rs 15 instead of Rs 20. Then we invent the decorator: a class that is a Beverage and has a Beverage, adds one thing, and passes the call inward. Then building the stack at runtime from the customer's order, java.io readers, Collections.unmodifiableList, why the order of wrapping matters, and Decorator vs inheritance. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs and error messages are real.

1. The real-life idea: the gift-wrapping counter

At the mall In code
The gift: a watch in a box The component: the object being decorated
Wrapping paper around the box A decorator: wraps the object and adds one thing; the watch inside is unchanged
A ribbon around the paper, a card on the ribbon Stacking: decorators wrap decorators, any number, any order
Still handed over as "a gift" Same interface: the client can't tell how many layers there are

2. The problem: add-ons at a chai stall

Ramesh's billing app has a Chai class: Rs 10. Customers want add-ons: ginger (+Rs 5), elaichi (cardamom, +Rs 5) and extra milk (+Rs 8).

First try: a subclass per combination

Using inheritance (a class extends another and gets its methods, episode 8), the obvious design is one subclass per combination. With 3 add-ons there are 2 × 2 × 2 = 8 combinations, so 8 classes. Then a customer orders a combination nobody wrote yet:

class Chai { int cost() { return 10; } String desc() { return "chai"; } }
class GingerChai extends Chai {
    int cost() { return 15; } String desc() { return "chai + ginger"; }
}
class MilkChai extends Chai {
    int cost() { return 18; } String desc() { return "chai + extra milk"; }
}
class GingerElaichiChai extends Chai {
    int cost() { return 20; } String desc() { return "chai + ginger + elaichi"; }
}
// ... ElaichiChai, ElaichiMilkChai, GingerElaichiMilkChai: 3 add-ons = 8 classes

public class Main {
    public static void main(String[] args) {
        Chai a = new GingerChai();
        System.out.println(a.desc() + " = Rs " + a.cost());
        Chai b = new GingerMilkChai();                 // a new customer's order
        System.out.println(b.desc() + " = Rs " + b.cost());
    }
}
Main.java:17: error: cannot find symbol
        Chai b = new GingerMilkChai();                 // a new customer's order
                     ^
  symbol:   class GingerMilkChai
  location: class Main
1 error

Class explosion means the number of classes grows much faster than the number of features: n add-ons need 2ⁿ classes (4 add-ons → 16, 5 → 32), and "double ginger" can't be expressed at all.

Second try: boolean flags

A boolean is a value that is either true or false. One Chai class with a flag per add-on:

class Chai {
    boolean ginger, elaichi, milk;                     // one flag per add-on
    int cost() {
        int c = 10;
        if (ginger) c += 5;
        if (elaichi) c += 5;
        if (milk) c += 8;
        return c;
    }
}

public class Main {
    public static void main(String[] args) {
        Chai c = new Chai();
        c.ginger = true;
        c.ginger = true;                               // "double ginger, please"
        System.out.println("double ginger chai = Rs " + c.cost());
    }
}
double ginger chai = Rs 15

Double ginger should be Rs 20. A flag is on or off; it can't count. And every new add-on (honey, tulsi, large size) means editing Chai, which breaks the Open-Closed Principle (episode 13: add behaviour without editing existing code).

Why both tries failed

  • Subclasses fix every combination at compile time (when the programmer writes and compiles the code).
  • But the customer chooses add-ons at runtime (while the program is running), in any number and order.
  • We want to start with a plain chai and add one thing at a time around it, like wrapping paper.

3. The fix: a decorator

interface Beverage { int cost(); String desc(); }     // the component

class Chai implements Beverage {                        // concrete component
    public int cost() { return 10; }
    public String desc() { return "chai"; }
}
abstract class AddOn implements Beverage {              // the decorator
    protected final Beverage inner;                     // wraps another Beverage
    AddOn(Beverage inner) { this.inner = inner; }
}
class Ginger extends AddOn {                            // concrete decorators
    Ginger(Beverage b) { super(b); }
    public int cost() { return inner.cost() + 5; }
    public String desc() { return inner.desc() + " + ginger"; }
}
class Milk extends AddOn {
    Milk(Beverage b) { super(b); }
    public int cost() { return inner.cost() + 8; }
    public String desc() { return inner.desc() + " + extra milk"; }
}

public class Main {
    public static void main(String[] args) {
        Beverage a = new Milk(new Ginger(new Chai()));
        System.out.println(a.desc() + " = Rs " + a.cost());
        Beverage b = new Ginger(new Ginger(new Chai()));   // double ginger
        System.out.println(b.desc() + " = Rs " + b.cost());
    }
}
chai + ginger + extra milk = Rs 23
chai + ginger + ginger = Rs 20

How it works:

  1. Beverage is an interface: a list of methods a class promises to have (episode 3).
  2. Chai implements Beverage: the plain object.
  3. AddOn implements Beverage and holds a Beverage in the field inner. It is a beverage and has a beverage. That double relationship is the whole pattern.
  4. Ginger.cost() asks inner.cost() and adds 5. It knows only its own price. Passing the call on to the inner object is called delegation or forwarding (episode 11).
  5. new Milk(new Ginger(new Chai())) builds the stack; new Ginger(new Ginger(new Chai())) is double ginger.

Four small classes now cover every combination. A new add-on is one new class; Chai is never edited.

4. It has a name: the Decorator pattern

Intent: the decorator pattern "allows behavior to be added to an individual object, dynamically", and it is "an alternative to subclassing" (Wikipedia, Decorator pattern). Dynamically means at runtime, for one object, not for the whole class.

Role Meaning In our code
Component The shared interface Beverage
Concrete component The plain object being decorated Chai
Decorator Implements the component and holds a component abstract class AddOn
Concrete decorator Adds exactly one thing, then forwards Ginger, Elaichi, Milk
Client Uses only the component interface main

AddOn is an abstract class (a class you can't create objects of directly; it exists to be extended, episode 3). It holds the shared inner field so each concrete decorator doesn't repeat it.

How one call flows

a.cost() on Milk(Ginger(Chai)):

Step Who Does
1 Client calls cost() on the outer layer, Milk
2 Milk asks inner.cost(), which is Ginger
3 Ginger asks inner.cost(), which is Chai
4 Chai returns 10
5 Ginger returns 10 + 5 = 15
6 Milk returns 15 + 8 = 23

The call travels in through each layer to the core, and the answer travels out, each layer adding its part.

5. Adding responsibilities at runtime

The program reads the customer's order as words from standard input (the input box in the compiler; elaichi milk ginger elaichi) and wraps one more decorator per word. The combination exists only at runtime:

import java.util.*;
interface Beverage { int cost(); String desc(); }
class Chai implements Beverage {
    public int cost() { return 10; }  public String desc() { return "chai"; }
}
abstract class AddOn implements Beverage {
    protected final Beverage inner;  AddOn(Beverage inner) { this.inner = inner; }
}
class Ginger extends AddOn { Ginger(Beverage b) { super(b); }
    public int cost() { return inner.cost() + 5; }
    public String desc() { return inner.desc() + " + ginger"; } }
class Elaichi extends AddOn { Elaichi(Beverage b) { super(b); }
    public int cost() { return inner.cost() + 5; }
    public String desc() { return inner.desc() + " + elaichi"; } }
class Milk extends AddOn { Milk(Beverage b) { super(b); }
    public int cost() { return inner.cost() + 8; }
    public String desc() { return inner.desc() + " + extra milk"; } }
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        Beverage order = new Chai();
        while (in.hasNext()) {                             // the customer decides, at runtime
            String w = in.next();
            if (w.equals("ginger"))  order = new Ginger(order);
            if (w.equals("elaichi")) order = new Elaichi(order);
            if (w.equals("milk"))    order = new Milk(order);
        }
        System.out.println(order.desc() + " = Rs " + order.cost());
    }
}

Input: elaichi milk ginger elaichi

chai + elaichi + extra milk + ginger + elaichi = Rs 33

10 + 5 + 8 + 5 + 5 = 33. No programmer planned this combination.

6. Decorators in java.io

"The I/O Streams implementations of both Java and the .NET Framework incorporate the decorator pattern" (Wikipedia). A Reader reads characters. StringReader reads from a string; BufferedReader wraps any Reader and adds readLine(); LineNumberReader wraps again and counts lines.

import java.io.*;

public class Main {
    public static void main(String[] args) throws IOException {
        Reader raw = new StringReader("Order 1: chai\nOrder 2: samosa\n");   // char by char
        BufferedReader buffered = new BufferedReader(raw);       // wraps it, adds readLine()
        LineNumberReader numbered = new LineNumberReader(buffered);   // wraps again, counts
        String line;
        while ((line = numbered.readLine()) != null) {
            System.out.println(numbered.getLineNumber() + " | " + line);
        }
        System.out.println(numbered instanceof Reader);   // still just a Reader
    }
}
1 | Order 1: chai
2 | Order 2: samosa
true

Reading a real file uses the same idea: new BufferedReader(new FileReader("menu.txt")). throws IOException says the method may throw a checked exception (episode 5) that callers must handle.

7. Collections.unmodifiableList: a decorator that says no

Collections.unmodifiableList(list) returns an object with the same List interface that wraps your list: it is a view, not a copy. Reads pass straight through; changes through the view throw UnsupportedOperationException; and changes to the original list show through the view.

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<String> menu = new ArrayList<>(List.of("chai", "samosa"));
        List<String> view = Collections.unmodifiableList(menu);   // a decorator around menu
        System.out.println(view + ", size " + view.size());       // reads pass through
        menu.add("vada pav");                                      // the owner changes the menu
        System.out.println("view now: " + view);                   // the view shows it
        view.add("pizza");                                         // a customer tries
    }
}
[chai, samosa], size 2
view now: [chai, samosa, vada pav]
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1092)
    at Main.main(Main.java:10)

Use it to hand out a read-only view of your internal list (encapsulation, episode 6) without copying it. If callers must not see later changes either, return a copy: List.copyOf(menu).

8. A logging decorator for payments

Decorators aren't only for chai. Priya's PaymentGateway (episode 27) needs a log (a written record of what the program did) before and after every payment. LoggingGateway implements PaymentGateway, holds one, logs, forwards, logs the result:

interface PaymentGateway { String pay(int paise, String upiId); }
class SimplePay implements PaymentGateway {                  // episode 27's gateway
    public String pay(int paise, String upiId) { return "paid Rs " + paise / 100; }
}
class LoggingGateway implements PaymentGateway {             // a decorator
    private final PaymentGateway inner;
    LoggingGateway(PaymentGateway inner) { this.inner = inner; }
    public String pay(int paise, String upiId) {
        System.out.println("LOG: " + upiId + " pays " + paise + " paise");
        String result = inner.pay(paise, upiId);              // forward the call
        System.out.println("LOG: result = " + result);
        return result;
    }
}
public class Main {
    static void checkout(PaymentGateway g) { g.pay(24000, "asha@upi"); }   // unchanged
    public static void main(String[] args) {
        checkout(new LoggingGateway(new SimplePay()));
    }
}
LOG: asha@upi pays 24000 paise
LOG: result = paid Rs 240

SimplePay and checkout were not edited. Behaviour that many classes need, such as logging, timing, retries and security checks, is called a cross-cutting concern; decorators (and next episode's proxies) are a clean way to add it. The mini project below adds a retry decorator on top.

9. The order of wrapping matters

Decorators don't always commute (give the same result in any order). A Rs 1000 bill, a flat Rs 100 coupon, and 5% GST (India's goods and services tax):

interface Bill { double total(); }
class Base implements Bill { public double total() { return 1000; } }
class Discount implements Bill {                     // a coupon
    final Bill in; Discount(Bill in) { this.in = in; }
    public double total() { return in.total() - 100; }  // a flat Rs 100 coupon
}
class Gst implements Bill {                          // 5% tax
    final Bill in; Gst(Bill in) { this.in = in; }
    public double total() { return in.total() * 1.05; }
}

public class Main {
    public static void main(String[] args) {
        System.out.println("coupon, then tax: Rs " + new Gst(new Discount(new Base())).total());
        System.out.println("tax, then coupon: Rs " + new Discount(new Gst(new Base())).total());
    }
}
coupon, then tax: Rs 945.0
tax, then coupon: Rs 950.0

Coupon then tax: (1000 − 100) × 1.05 = 945. Tax then coupon: 1000 × 1.05 − 100 = 950. Build the stack in one place that follows the business rule, and test it.

10. Decorator vs inheritance

Inheritance (subclass per combination) Decorator
When behaviour is chosen Compile time Runtime
Applies to The whole class One object
Classes for n add-ons up to 2ⁿ n
Repeat an add-on (double ginger) Impossible new Ginger(new Ginger(...))
Downsides Class explosion, edits for every new mix Many small objects; stack traces pass through several layers; order matters

This is composition over inheritance (episode 11) again: combining objects instead of extending classes.

11. Decorator vs Adapter vs Proxy

Pattern Interface Job Example
Decorator same adds behaviour Ginger, BufferedReader, unmodifiableList
Adapter (episode 27) changes it makes a class fit an expected interface BankSdkAdapter
Proxy (episode 29) same controls access: lazy creation, permissions, caching PhotoProxy

Common mistakes

Mistake Exact message / symptom Why Fix
A subclass per combination error: cannot find symbol … symbol: class GingerMilkChai Combinations are picked at runtime One decorator per add-on, wrap as needed
Boolean flags for add-ons no error: double ginger chai = Rs 15 A flag can't count; new add-ons edit Chai Wrap twice: new Ginger(new Ginger(chai))
Writing through an unmodifiable view java.lang.UnsupportedOperationException The decorator blocks writes Change the original, or copy it
Wrapping in the wrong order no error: Rs 950.0 instead of Rs 945.0 Decorators don't always commute Build the stack in one place; test it
Decorator that forgets to forward no error: chai + ginger costs Rs 5 cost() returned 5 instead of inner.cost() + 5 Always call inner
Decorator that doesn't implement the component incompatible types: Ginger cannot be converted to Beverage It can't be wrapped again or used by clients implements Beverage (via AddOn)

Mini project: a logging and retry decorator for payments

Priya's checkout uses PaymentGateway { String pay(int paise, String upiId); }. Write two decorators: LoggingGateway (prints a line before and after every payment) and RetryGateway (retries up to 3 times if the inner gateway throws). Test them with a FlakyPay gateway that fails the first two times.

Solution
interface PaymentGateway { String pay(int paise, String upiId); }

class FlakyPay implements PaymentGateway {                 // fails twice, then works
    int tries = 0;
    public String pay(int paise, String upiId) {
        tries++;
        if (tries < 3) throw new IllegalStateException("bank busy (try " + tries + ")");
        return "paid Rs " + paise / 100 + " from " + upiId;
    }
}
class LoggingGateway implements PaymentGateway {
    private final PaymentGateway inner;
    LoggingGateway(PaymentGateway inner) { this.inner = inner; }
    public String pay(int paise, String upiId) {
        System.out.println("LOG: paying " + paise + " paise for " + upiId);
        String r = inner.pay(paise, upiId);
        System.out.println("LOG: result = " + r);
        return r;
    }
}
class RetryGateway implements PaymentGateway {
    private final PaymentGateway inner; private final int max;
    RetryGateway(PaymentGateway inner, int max) { this.inner = inner; this.max = max; }
    public String pay(int paise, String upiId) {
        for (int i = 1; ; i++) {
            try { return inner.pay(paise, upiId); }
            catch (IllegalStateException e) {
                System.out.println("  retry after: " + e.getMessage());
                if (i == max) throw e;
            }
        }
    }
}
public class Main {
    public static void main(String[] args) {
        PaymentGateway g = new LoggingGateway(new RetryGateway(new FlakyPay(), 3));
        System.out.println(g.pay(24000, "asha@upi"));
    }
}
LOG: paying 24000 paise for asha@upi
  retry after: bank busy (try 1)
  retry after: bank busy (try 2)
LOG: result = paid Rs 240 from asha@upi
paid Rs 240 from asha@upi

The log is written once, outside the retries, because LoggingGateway is the outer layer. Swap the order (new RetryGateway(new LoggingGateway(...), 3)) and you get a log line for every attempt: the order of wrapping matters here too.

Practice

1. Add Honey (+Rs 7). Which existing classes change?

Answer

None. Write class Honey extends AddOn { Honey(Beverage b) { super(b); } public int cost() { return inner.cost() + 7; } public String desc() { return inner.desc() + " + honey"; } }.

2. Write a Large decorator that doubles the price of everything inside it. What is new Large(new Ginger(new Chai())).cost(), and what is new Ginger(new Large(new Chai())).cost()?

Answer

cost() returns inner.cost() * 2. Large around ginger chai: (10 + 5) × 2 = 30. Ginger around large chai: 10 × 2 + 5 = 25. Order matters.

3. Why is AddOn abstract?

Answer

It has no price of its own; it exists only to share the inner field and constructor with the concrete decorators. Making it abstract stops anyone from creating a meaningless new AddOn(chai).

4. A colleague writes class Ginger extends Chai "to reuse cost()". What goes wrong?

Answer

Ginger now is a plain Chai and can't wrap anything else (milk chai, elaichi chai). You are back to one subclass per combination. A decorator must hold the component, not extend the concrete one.

5. List<String> v = Collections.unmodifiableList(menu); menu.clear(); What does v.size() return?

Answer

0. The view wraps the same list, so the original's changes show through.

Quick quiz

Beverage b = new Ginger(new Milk(new Ginger(new Chai())));
System.out.println(b.cost());

// Chai = 10, Ginger = +5, Milk = +8
  • A. 15
  • B. 23
  • C. 28
  • D. Compile error: Ginger used twice
Answer

C, 28. 10 + 5 + 8 + 5. Each layer adds its price; the same decorator can wrap more than once.

Interview questions

  1. What is the Decorator pattern? A structural pattern that adds behaviour to an individual object at runtime by wrapping it in an object with the same interface, as an alternative to subclassing.
  2. Name the participants. Component, concrete component, decorator, concrete decorator (and the client).
  3. Why does the decorator implement the component and hold one? Implementing it lets the decorated object be used (and wrapped again) anywhere a component is expected; holding one lets it forward calls to the object inside.
  4. What problem does it solve over inheritance? Class explosion (2ⁿ subclasses for n options) and compile-time-only combinations.
  5. Examples in the JDK? java.io readers and streams (BufferedReader, LineNumberReader, BufferedInputStream), Collections.unmodifiableList, Collections.synchronizedList.
  6. Does wrapping order matter? It can: discount-then-tax differs from tax-then-discount; logging outside vs inside retries.
  7. Decorator vs Adapter? Decorator keeps the interface and adds behaviour; Adapter changes the interface.
  8. Decorator vs Proxy? Both keep the interface. Decorator adds behaviour and the client usually builds the stack; Proxy controls access and often creates or owns the real object.
  9. Downsides? Many small objects, harder debugging through layers, order-sensitive results, identity checks (==) on the wrapper aren't the inner object.
  10. How would you add logging to every payment without editing gateways? A LoggingGateway decorator that implements PaymentGateway, logs, and forwards.

Glossary

Term Meaning, with an example
Decorator pattern Wrap an object in another object with the same interface that adds one behaviour. new Ginger(chai)
Component The shared interface of plain and decorated objects. Beverage
Concrete component The plain object at the core. Chai
Decorator A class that implements the component and holds a component. AddOn
Concrete decorator A decorator that adds exactly one thing. Ginger, Milk
Wrapping Putting one object inside another that forwards calls to it
Stacking decorators Wrapping a decorated object again. new Milk(new Ginger(new Chai()))
Adding responsibilities at runtime Choosing behaviour while the program runs, for one object, e.g. from the customer's order
Class explosion Classes multiplying for every combination: 3 add-ons → 8 subclasses
Inheritance A class extends another and reuses its code (episode 8)
Composition over inheritance Prefer holding objects to extending classes (episode 11)
Delegation / forwarding Passing a call on to the inner object. inner.cost()
Boolean flag A true/false field that switches a feature on or off
Compile time / runtime When code is compiled / when the program is running
Open-Closed Principle Add behaviour without editing existing code (episode 13)
Interface A list of methods a class promises to implement (episode 3)
Abstract class A class that can't be instantiated, only extended (episode 3)
java.io Java's input/output library: readers, writers, streams
Reader / StringReader A character input source / one that reads from a String
BufferedReader A Reader decorator that reads in chunks and adds readLine()
LineNumberReader A Reader decorator that counts lines: getLineNumber()
Collections.unmodifiableList Returns a read-only view that wraps a list
View An object that shows another object's data without copying it
UnsupportedOperationException Thrown when an object refuses an optional operation, e.g. add on a read-only view
Commute Give the same result in either order; decorators often don't
GST Goods and services tax, India's tax on sales; 5% in our example
Elaichi Cardamom, a spice added to chai
Log A written record of what the program did. LOG: asha@upi pays 24000 paise
Cross-cutting concern Behaviour many classes need (logging, timing, retries); added with decorators or proxies
Standard input The text a program reads while running (the compiler's input box)

Summary

  • Subclass per combination explodes (2ⁿ classes) and can't express runtime choices; flags can't count and force edits.
  • A decorator implements the component and holds one; it adds one behaviour and forwards the call inward.
  • Stack decorators in any number and order; build the stack at runtime from user choices.
  • Decorators add cross-cutting concerns like logging to any interface without editing the wrapped class.
  • java.io readers and Collections.unmodifiableList are decorators in the JDK.
  • Wrapping order can change results: build stacks in one place and test them.
  • Decorator adds behaviour (same interface); Adapter changes the interface; Proxy controls access.

Next episode: The Proxy pattern.