Skip to lesson

Decorator: adding behaviour without subclassing

ShopLite's payment code needs logging, retry and timing. Typed into the gateway class, they bury the real work and force an edit for every new extra. Is there a cleaner way?

The problem: extra behaviour around payments

A decorator wraps an object, has the same interface as it, and adds behaviour before or after passing each call on.

ShopLite's payment code now needs logging, retry and timing. Example 1 shows the quick fix: typing all three into the gateway class.

Example 1 · Without decorators: extras mixed into the gateway

MixedExtrasDemo.javaJava
record PaymentResult(boolean success, String message) {}
interface PaymentGateway {    PaymentResult pay(String orderId, int rupees);}
class PayNowGateway implements PaymentGateway {    @Override    public PaymentResult pay(String orderId, int rupees) {        System.out.println("[log] pay " + orderId + " Rs " + rupees);     // logging        PaymentResult result = null;        for (int attempt = 1; attempt <= 3; attempt++) {                 // retry            result = callBank(orderId, rupees, attempt);            if (result.success()) {                break;            }        }        System.out.println("[log] " + orderId + " -> " + result.message()); // logging        return result;    }
    private PaymentResult callBank(String orderId, int rupees, int attempt) {        if (attempt == 1) {            System.out.println("  bank: timeout");            return new PaymentResult(false, "timeout");        }        System.out.println("  bank: charged Rs " + rupees);        return new PaymentResult(true, "paid");    }}
public class MixedExtrasDemo {    public static void main(String[] args) {        PaymentGateway gateway = new PayNowGateway();        gateway.pay("A101", 1499);    }}
Output
[log] pay A101 Rs 1499
  bank: timeout
  bank: charged Rs 1499
[log] A101 -> paid

What this code does

  • The only real payment work is callBank. Everything else in pay is logging and retry, mixed into the same method.
  • To log without retry, or to add timing, you must edit this working class again. Every other gateway (UPI, wallet) would need the same loops copied in.

These extras are cross-cutting jobs: none is about payment itself, and many classes need them. In the quick fix the real payment call is buried under loops and print lines, you cannot switch retry off for UPI only, and every new extra means editing a class that already works.

Decorator: same interface, wraps another instance

A component is the shared interface (here PaymentGateway) that the real object and every decorator implement.

LoggingGateway implements PaymentGateway and keeps another gateway in a field called inner. Example 2 wraps the real gateway in it without editing that class.

Example 2 · A LoggingGateway decorator

LoggingDecoratorDemo.javaJava
record PaymentResult(boolean success, String message) {}
interface PaymentGateway {    PaymentResult pay(String orderId, int rupees);}
class PayNowGateway implements PaymentGateway {    @Override    public PaymentResult pay(String orderId, int rupees) {        System.out.println("  bank: charged Rs " + rupees);        return new PaymentResult(true, "paid");    }}
class LoggingGateway implements PaymentGateway {    private final PaymentGateway inner;
    LoggingGateway(PaymentGateway inner) {        this.inner = inner;    }
    @Override    public PaymentResult pay(String orderId, int rupees) {        System.out.println("[log] pay " + orderId + " Rs " + rupees);   // before        PaymentResult result = inner.pay(orderId, rupees);              // delegate once        System.out.println("[log] " + orderId + " -> " + result.message()); // after        return result;    }}
class Checkout {    private final PaymentGateway gateway;
    Checkout(PaymentGateway gateway) {        this.gateway = gateway;    }
    void placeOrder(String orderId, int rupees) {        if (gateway.pay(orderId, rupees).success()) {            System.out.println("Order " + orderId + " confirmed");        }    }}
public class LoggingDecoratorDemo {    public static void main(String[] args) {        new Checkout(new PayNowGateway()).placeOrder("A101", 1499);        System.out.println("---");        new Checkout(new LoggingGateway(new PayNowGateway())).placeOrder("A102", 899);    }}
Output
  bank: charged Rs 1499
Order A101 confirmed
---
[log] pay A102 Rs 899
  bank: charged Rs 899
[log] A102 -> paid
Order A102 confirmed

What this code does

  • LoggingGateway is a PaymentGateway that holds another PaymentGateway. It prints before and after, and in between it calls inner.pay once.
  • Checkout and PayNowGateway did not change at all. Logging was switched on for the second checkout only by wrapping the gateway.

Checkout still sees only a PaymentGateway, so it does not know that a decorator sits in front of the real one. The roles:

  • Component: the interface (PaymentGateway).
  • Concrete component: the real object (PayNowGateway).
  • Decorator: implements the interface and wraps a component (LoggingGateway).
  • Rule: call inner exactly once per call, unless skipping or repeating is the decorator's job (like retry).

Find the bug

Find the delegation bug

Each decorator method has one wrong line. Click it.

No payment ever reaches the bank, but orders look paid.

Round 1 of 2

Stacking decorators: order matters

Stacked decorators are wrapped inside one another. The call travels from the outermost layer inward, and the result comes back from the inside out.

A decorator is itself a PaymentGateway, so it can be wrapped again: new LoggingGateway(new RetryGateway(bank, 3)). Example 3 runs the same two decorators in both orders.

A stack of decorators around a payment gateway. Checkout calls LoggingGateway, which calls RetryGateway, which calls PayNowGateway, the real object. The call travels inward through each layer and the result travels back outward, so each decorator can add work before and after.

Example 3 · Same decorators, two orders, different output

DecoratorOrderDemo.javaJava
record PaymentResult(boolean success, String message) {}
interface PaymentGateway {    PaymentResult pay(String orderId, int rupees);}
class FlakyBank implements PaymentGateway {            // times out the first time    private int failuresLeft;
    FlakyBank(int failures) {        this.failuresLeft = failures;    }
    @Override    public PaymentResult pay(String orderId, int rupees) {        if (failuresLeft > 0) {            failuresLeft--;            System.out.println("  bank: timeout");            return new PaymentResult(false, "timeout");        }        System.out.println("  bank: charged Rs " + rupees);        return new PaymentResult(true, "paid");    }}
class LoggingGateway implements PaymentGateway {    private final PaymentGateway inner;
    LoggingGateway(PaymentGateway inner) {        this.inner = inner;    }
    @Override    public PaymentResult pay(String orderId, int rupees) {        PaymentResult result = inner.pay(orderId, rupees);        System.out.println("[log] " + orderId + " -> " + result.message());        return result;    }}
class RetryGateway implements PaymentGateway {    private final PaymentGateway inner;    private final int maxAttempts;
    RetryGateway(PaymentGateway inner, int maxAttempts) {        this.inner = inner;        this.maxAttempts = maxAttempts;    }
    @Override    public PaymentResult pay(String orderId, int rupees) {        PaymentResult result = inner.pay(orderId, rupees);        for (int attempt = 2; attempt <= maxAttempts && !result.success(); attempt++) {            System.out.println("[retry] attempt " + attempt);            result = inner.pay(orderId, rupees);        }        return result;    }}
public class DecoratorOrderDemo {    public static void main(String[] args) {        System.out.println("Logging outside retry:");        PaymentGateway a = new LoggingGateway(new RetryGateway(new FlakyBank(1), 3));        a.pay("A101", 1499);
        System.out.println("Retry outside logging:");        PaymentGateway b = new RetryGateway(new LoggingGateway(new FlakyBank(1)), 3);        b.pay("A102", 1499);    }}
Output
Logging outside retry:
  bank: timeout
[retry] attempt 2
  bank: charged Rs 1499
[log] A101 -> paid
Retry outside logging:
  bank: timeout
[log] A102 -> timeout
[retry] attempt 2
  bank: charged Rs 1499
[log] A102 -> paid

What this code does

  • In a, logging wraps the whole retry loop, so it sees only the final result: one log line, paid.
  • In b, retry calls the logging decorator on every attempt, so the failed attempt is logged too. Same three classes, different order, different output.

A call travels from the outside in, and the result travels back from the inside out, like layers of an onion.

The order changes the behaviour. With logging outside retry, you see one log line per order. With retry outside logging, every attempt is logged. Neither is wrong; choose the order that gives the behaviour you want.

Predict the output

How many log lines?

The bank fails twice, then succeeds. [log] prints one line per call it sees.

Round 1 of 2

Logging is the outer layer.

PaymentGateway g = new LoggingGateway(new RetryGateway(bank, 3));
g.pay("A1", 500);

Decorator vs subclassing: avoiding the class explosion

A class explosion is one subclass for every combination of extras: 2ⁿ − 1 classes for n extras.

Inheritance needs a subclass for every combination: LoggingPayNowGateway, RetryingPayNowGateway, LoggingRetryingPayNowGateway and so on. Example 4 builds the combination from a setting instead.

Example 4 · Choosing the extras at runtime from a setting

RuntimeDecoratorsDemo.javaJava
import java.util.List;import java.util.function.LongSupplier;record PaymentResult(boolean success, String message) {}
interface PaymentGateway {    PaymentResult pay(String orderId, int rupees);}
class PayNowGateway implements PaymentGateway {    @Override    public PaymentResult pay(String orderId, int rupees) {        System.out.println("  bank: charged Rs " + rupees);        return new PaymentResult(true, "paid");    }}
class LoggingGateway implements PaymentGateway {    private final PaymentGateway inner;
    LoggingGateway(PaymentGateway inner) {        this.inner = inner;    }
    @Override    public PaymentResult pay(String orderId, int rupees) {        PaymentResult result = inner.pay(orderId, rupees);        System.out.println("[log] " + orderId + " -> " + result.message());        return result;    }}
class TimingGateway implements PaymentGateway {    private final PaymentGateway inner;    private final LongSupplier clock;                 // gives the time in milliseconds
    TimingGateway(PaymentGateway inner, LongSupplier clock) {        this.inner = inner;        this.clock = clock;    }
    @Override    public PaymentResult pay(String orderId, int rupees) {        long start = clock.getAsLong();        PaymentResult result = inner.pay(orderId, rupees);        System.out.println("[time] " + orderId + " took " + (clock.getAsLong() - start) + " ms");        return result;    }}
public class RuntimeDecoratorsDemo {    static PaymentGateway build(List<String> extras, LongSupplier clock) {        PaymentGateway gateway = new PayNowGateway();        for (String extra : extras) {                 // each extra wraps the one before            gateway = switch (extra) {                case "log" -> new LoggingGateway(gateway);                case "time" -> new TimingGateway(gateway, clock);                default -> throw new IllegalArgumentException("unknown extra: " + extra);            };        }        return gateway;    }
    public static void main(String[] args) {        long[] fakeNow = {0};        LongSupplier clock = () -> fakeNow[0] += 40;  // fake clock: each read moves 40 ms on
        System.out.println("UPI settings [log]:");        build(List.of("log"), clock).pay("U1", 250);
        System.out.println("Card settings [log, time]:");        build(List.of("log", "time"), clock).pay("C1", 2999);    }}
Output
UPI settings [log]:
  bank: charged Rs 250
[log] U1 -> paid
Card settings [log, time]:
  bank: charged Rs 2999
[log] C1 -> paid
[time] C1 took 40 ms

What this code does

  • build wraps the real gateway once per name in the list, so the set of extras comes from data, not from a fixed subclass. With subclasses you would need a class for every combination.
  • In real code the clock is System::currentTimeMillis. The demo passes a fake clock that moves 40 ms per read, so the output is the same on every run; that is also how you test a timing decorator.

Three optional extras give 7 combinations per gateway, and two gateways give 14 classes. With decorators you write each extra once (3 classes) and combine them when the program starts, even from a configuration value.

Inheritance fixes the combination when you compile; decorators choose it at runtime.

Price decorators: gift wrap and express delivery

Decorators are not only technical. Example 5 wraps a cart item in GiftWrap (Rs 49) and ExpressDelivery (Rs 99) add-ons that change its price and description.

Example 5 · Price add-ons: GiftWrap and ExpressDelivery

AddOnDemo.javaJava
interface CartItem {    String description();    int price();}
class Product implements CartItem {    private final String name;    private final int price;
    Product(String name, int price) {        this.name = name;        this.price = price;    }
    public String description() { return name; }    public int price() { return price; }}
abstract class AddOn implements CartItem {           // shared base for price decorators    protected final CartItem item;
    AddOn(CartItem item) {        this.item = item;    }}
class GiftWrap extends AddOn {    GiftWrap(CartItem item) { super(item); }
    public String description() { return item.description() + " + gift wrap"; }    public int price() { return item.price() + 49; }}
class ExpressDelivery extends AddOn {    ExpressDelivery(CartItem item) { super(item); }
    public String description() { return item.description() + " + express delivery"; }    public int price() { return item.price() + 99; }}
public class AddOnDemo {    static void show(CartItem item) {        System.out.println(item.description() + " = Rs " + item.price());    }
    public static void main(String[] args) {        show(new Product("Smart watch", 2999));        show(new GiftWrap(new Product("Smart watch", 2999)));        show(new ExpressDelivery(new GiftWrap(new Product("Earbuds", 1499))));    }}
Output
Smart watch = Rs 2999
Smart watch + gift wrap = Rs 3048
Earbuds + gift wrap + express delivery = Rs 1647

What this code does

  • Each add-on asks the item it wraps for its price and description, then adds its own part. The innermost Product is always reached at the end of the chain.
  • AddOn holds the shared item field and constructor, so GiftWrap and ExpressDelivery contain only what they change.

When several decorators share the same field and constructor, put them in an abstract base class such as AddOn. Each add-on then overrides only the methods it changes.

Next step

Check your understanding

12 quick questions