LLD

Structural Patterns

Decorator pattern

Caching, retries and timing all wrap the same call, and different callers want different mixes of them. We build a price lookup twice, once as one class full of flags and once as a stack of small layers, and look at where the order of the layers matters.

A checkout page shows the price of every item in the cart. The prices come from another team's pricing service, over the network. That service is usually fast, sometimes slow, and now and then it times out. So the code that asks for a price soon needs more than the call itself. It needs a cache, so the same chair is not priced twice in a minute. It needs retries, so one timeout does not break the page. It needs timing, so someone can see when the service gets slow.

None of these jobs is about prices. Each one wraps the call and does something before or after it. The same thing happens with a database client that needs logging and metrics, a file reader that needs buffering, or a web request that needs authentication and rate limiting. And different callers want different mixes: the admin page wants fresh prices with no cache, and a nightly report wants retries but no timing.

The Decorator pattern turns each of these jobs into its own small class that wraps the next one. In this article we build a price lookup twice. The first version is one class with a flag for each job. The second stacks three small layers. Then we look at what the order of the layers changes, what the pattern costs, and how it differs from a Proxy.

All the code is Java, and all of it compiles and runs. Every snippet is cut from a project that compiles, except the ones labelled Sketch. Most come from the finished project, where the Open file button shows the whole file in a code browser. The first version's snippets come from a separate, simpler project.

The price lookup we are building

The lookup must:

  1. Return the price of a product by its code, its SKU, in cents.
  2. Keep each price for 5 minutes, so a refresh or a second cart line does not call the service again.
  3. When the service times out, try again: up to 3 attempts in total, waiting 100 ms and then 200 ms between them.
  4. Never retry when the product does not exist. Asking again cannot change that answer.
  5. Record how long each lookup took, and whether it worked.
  6. Let a different caller switch any of these off, or put them in a different order, without editing the others.
One price lookup, with every job
Timing starts first (1). The cache answers straight away if it holds a price younger than 5 minutes (2). On a miss, the remote service is called (3). A timeout leads to a wait and another attempt, up to 3 in all (4). A price that comes back is stored in the cache (5). Whatever happened, the time taken and the outcome are recorded on the way out (6).Timing starts first (1). The cache answers straight away if it holds a price younger than 5 minutes (2). On a miss, the remote service is called (3). A timeout leads to a wait and another attempt, up to 3 in all (4). A price that comes back is stored in the cache (5). Whatever happened, the time taken and the outcome are recorded on the way out (6).
Three jobs wrap one remote call, and each one runs before or after it. Timing starts first (1). The cache answers straight away if it holds a price younger than 5 minutes (2). On a miss, the remote service is called (3). A timeout leads to a wait and another attempt, up to 3 in all (4). A price that comes back is stored in the cache (5). Whatever happened, the time taken and the outcome are recorded on the way out (6).

Read the figure from the outside in. Timing is the outer ring: it starts before everything and finishes after everything. The cache sits inside it and can answer without going further. Retries sit closest to the remote call. Every job is wrapped around the jobs inside it. That nesting is what the pattern turns into code.

The first version: one class with flags

The obvious way to write this is one class with a boolean for each job, and one method that checks the flags:

PriceClient.javalines 7–27 of 63
public class PriceClient {    private final PriceService remote;    private final boolean caching;    private final boolean retrying;    private final boolean timing;    private final Clock clock;    private final Sleeper sleeper;    private final CallLog log;    private final Map<String, Long> cachedPrices = new HashMap<>();    private final Map<String, Instant> cachedAt = new HashMap<>();     public PriceClient(PriceService remote, boolean caching, boolean retrying, boolean timing,                       Clock clock, Sleeper sleeper, CallLog log) {        this.remote = remote;        this.caching = caching;        this.retrying = retrying;        this.timing = timing;        this.clock = clock;        this.sleeper = sleeper;        this.log = log;    }

And here is the method that does the work:

PriceClient.javalines 29–62 of 63
    public long priceOf(String sku) {        Instant start = clock.instant();        boolean succeeded = false;        try {            if (caching && cachedPrices.containsKey(sku)                    && clock.instant().isBefore(cachedAt.get(sku).plus(Duration.ofMinutes(5)))) {                succeeded = true;                return cachedPrices.get(sku);            }            int attempts = retrying ? 3 : 1;            Duration wait = Duration.ofMillis(100);            for (int attempt = 1; ; attempt++) {                try {                    long price = remote.priceOf(sku);                    if (caching) {                        cachedPrices.put(sku, price);                        cachedAt.put(sku, clock.instant());                    }                    succeeded = true;                    return price;                } catch (PriceLookupException e) {                    if (attempt == attempts) {                        throw e;                    }                    sleeper.sleep(wait);                    wait = wait.multipliedBy(2);                }            }        } finally {            if (timing) {                log.record(sku, Duration.between(start, clock.instant()), succeeded);            }        }    }

This code works, and for one caller that wants all three jobs forever, it is fine. The trouble starts when the needs change.

The jobs are tangled. The cache check sits inside the timing try block. The cache store sits inside the retry loop. To understand the retry rule, you have to read past the cache code, and to change the cache, you have to be careful not to break the retry loop around it.

The order is fixed in the code. Timing wraps everything, because the method was written that way. A caller that wants to time each remote attempt separately needs a different method.

Every new job edits the same method. A rate limit would be a fourth flag and more ifs inside the same 30 lines. Every flag also doubles the cases to test: three flags give 8 combinations.

The usual way out of the flags is a subclass for each combination, and that is worse:

Subclasses or layers
On the left, every combination of caching, retrying and timing is its own subclass of PriceClient, seven in all, and a fourth job would make fifteen. Each one repeats code from the others. On the right, each job is one class that wraps any PriceService. Three classes cover every combination and every order.On the left, every combination of caching, retrying and timing is its own subclass of PriceClient, seven in all, and a fourth job would make fifteen. Each one repeats code from the others. On the right, each job is one class that wraps any PriceService. Three classes cover every combination and every order.
Three optional jobs need seven subclasses, but only three layers. On the left, every combination of caching, retrying and timing is its own subclass of PriceClient, seven in all, and a fourth job would make fifteen. Each one repeats code from the others. On the right, each job is one class that wraps any PriceService. Three classes cover every combination and every order.

The idea

The pattern works like this:

  • Every layer implements the same interface as the thing it wraps. Here that interface is PriceService, with one method, priceOf.
  • Each layer holds one inner PriceService, given to it in its constructor.
  • A layer does its one extra job, and calls the inner service for the real answer.
  • The caller holds the outermost layer, and cannot tell how many layers are inside it.
  • The layers are stacked in one place, at startup, and the order is a decision made there.

Each layer is a decorator: it adds behaviour to an object without changing that object's class. The interface they all share, PriceService, is the component, and sharing it is what lets them stack. The real client at the centre, the one that calls the pricing service, is the concrete component.

Building it, step by step

Step 1: one small interface

Everything starts from the interface that the real client and every layer implement:

price/PriceService.javalines 3–6 of 6
public interface PriceService {    // Returns the price in cents. Throws PriceLookupException or UnknownProductException.    long priceOf(String sku);}

The interface has one method, priceOf, which returns cents. The real client that calls the pricing service over the network belongs to the pricing team and is not in this project. The demo uses a fake, FlakyPriceService, that implements the same interface. priceOf can throw two exceptions: PriceLookupException when the service failed to answer, and UnknownProductException when it answered "no such product". The difference between the two matters to the retry layer.

A small interface keeps every layer small. Every layer needs every method of the interface, unless the interface supplies a default body, so if PriceService had ten methods, every layer would forward nine of them untouched.

Decision

Should the layers share a base class?

An abstract PriceServiceDecorator that holds the inner service and forwards every method

Each layer then overrides only the method it changes. This pays off when the interface is large: a stream or a collection can have a dozen methods, and writing a dozen forwarding methods in every layer is noise.

Each layer implements PriceService directlyOur pick

The interface has one method, so a base class would save nothing and add a class to read. Each layer holds its own inner field and is complete on its own page. If the interface grows, a base class becomes worth it.

Step 2: the retry layer

The first layer retries a lookup that timed out:

layer/RetryingPriceService.javalines 9–57 of 57
public class RetryingPriceService implements PriceService {    private final PriceService inner;    private final int maxAttempts;    private final Duration firstWait;    private final Duration maxWait;    private final Sleeper sleeper;     public RetryingPriceService(PriceService inner, int maxAttempts,                                Duration firstWait, Duration maxWait, Sleeper sleeper) {        this.inner = Objects.requireNonNull(inner, "inner");        this.firstWait = Objects.requireNonNull(firstWait, "firstWait");        this.maxWait = Objects.requireNonNull(maxWait, "maxWait");        this.sleeper = Objects.requireNonNull(sleeper, "sleeper");        if (maxAttempts < 1) {            throw new IllegalArgumentException("maxAttempts must be at least 1, got " + maxAttempts);        }        if (firstWait.isNegative() || firstWait.isZero()) {            throw new IllegalArgumentException("firstWait must be positive, got " + firstWait);        }        if (maxWait.compareTo(firstWait) < 0) {            throw new IllegalArgumentException("maxWait must be at least firstWait, got " + maxWait);        }        this.maxAttempts = maxAttempts;    }     @Override    public long priceOf(String sku) {        Duration wait = firstWait;        for (int attempt = 1; ; attempt++) {            try {                return inner.priceOf(sku);            } catch (PriceLookupException e) {                if (attempt == maxAttempts) {                    throw e;                }                sleeper.sleep(wait);                wait = nextWait(wait);            }        }    }     // Doubles the wait up to maxWait. Comparing first means the doubling can never overflow.    private Duration nextWait(Duration wait) {        if (wait.compareTo(maxWait.dividedBy(2)) > 0) {            return maxWait;        }        return wait.multipliedBy(2);    }}

The loop calls the inner service. If a price comes back, it returns it. If the inner service throws PriceLookupException, the layer waits and tries again, doubling the wait each time: 100 ms, then 200 ms. nextWait stops the doubling at maxWait, 1 second for checkout, so a layer set to many attempts never waits minutes, and the doubling can never overflow. On the last attempt it throws the same exception the inner service threw, so the caller sees the real reason.

Line 40 is the important one. The layer catches only PriceLookupException. An UnknownProductException is not caught, so it passes straight through on the first attempt. Asking for a product that does not exist three times would only make the caller wait at least 300 ms longer for the same "no": two waits and two more calls, 380 ms with the demo's timings.

The constructor checks everything it is given: Objects.requireNonNull on each collaborator, a positive first wait, and a cap no smaller than it. A stack built wrong fails when it is built, not on the first lookup at checkout. The other two layers check their arguments the same way.

The wait goes through a Sleeper interface instead of Thread.sleep. The demo and the tests pass a sleeper that only moves a fake clock forward, so nothing waits for real. Production passes one that really sleeps, and it has to handle being interrupted:

Sketchnot part of the final code
public void sleep(Duration duration) {    try {        Thread.sleep(duration.toMillis());    } catch (InterruptedException e) {        Thread.currentThread().interrupt();        throw new IllegalStateException("Interrupted while waiting to retry", e);    }}

It sets the thread's interrupted flag again, so code further up can see it, and throws. That exception is not a PriceLookupException, so it leaves the retry loop at once and no further attempt is made.

Decision

Which failures does the retry layer retry?

Every exception

This is simple, and it seems safe. But some failures are permanent: an unknown product, a bad request, a permission error. Retrying them makes every such answer three times slower and puts extra load on a service that may already be struggling.

Only PriceLookupException, the temporary kindOur pick

The inner service already tells us which failures are worth another try, through the exception type. The retry layer trusts that. Anything else passes through untouched, on the first attempt.

Step 3: the cache layer

The second layer keeps each price for a while:

layer/CachingPriceService.javalines 12–42 of 42
public class CachingPriceService implements PriceService {    private record Entry(long price, Instant storedAt) {    }     private final PriceService inner;    private final Duration timeToLive;    private final Clock clock;    private final Map<String, Entry> cache = new ConcurrentHashMap<>();     public CachingPriceService(PriceService inner, Duration timeToLive, Clock clock) {        this.inner = Objects.requireNonNull(inner, "inner");        this.timeToLive = Objects.requireNonNull(timeToLive, "timeToLive");        this.clock = Objects.requireNonNull(clock, "clock");        if (timeToLive.isNegative() || timeToLive.isZero()) {            throw new IllegalArgumentException("timeToLive must be positive, got " + timeToLive);        }    }     @Override    public long priceOf(String sku) {        Instant now = clock.instant();        Entry entry = cache.get(sku);        if (entry != null && now.isBefore(entry.storedAt().plus(timeToLive))) {            return entry.price();        }        // Only a price that came back is stored. A failure throws past this line.        long price = inner.priceOf(sku);        cache.put(sku, new Entry(price, clock.instant()));        return price;    }}

On every lookup, the layer checks its map. If it holds a price for this SKU, stored less than 5 minutes ago, it returns that price and never calls the inner service. Otherwise it calls the inner service, stores what comes back with the current time, and returns it.

Three details matter here.

  • A price exactly 5 minutes old counts as expired. isBefore is false at exactly 5 minutes, so the layer fetches a new one. The age counts from when the price came back (line 39 reads the clock again), not from when it was asked for.
  • Only prices are stored. If the inner service throws, the exception leaves the method before line 39, so nothing is cached. The next lookup tries the service again.
  • The map is a ConcurrentHashMap, because one cache is shared by every checkout request at once. Two requests can read and write it at the same time safely. Two requests that miss on the same SKU at the same moment both call the service, though. For prices that is fine. A cache in front of something expensive would need to make the second request wait for the first one's answer.
  • The map never shrinks. Every SKU ever priced stays in it, and an expired price is only replaced when someone asks for that SKU again. For a catalogue of a few thousand products that is fine. A larger one needs a size limit with eviction, a bounded map, such as an LRU, inside this layer. A separate layer cannot do it, because it has no way into this layer's private map.

The cache reads the time from a Clock that is passed in, never from Instant.now(). A test can then move the clock forward 5 minutes in one line.

Step 4: the timing layer

The third layer records how long each lookup took:

layer/TimingPriceService.javalines 21–40 of 41
    @Override    public long priceOf(String sku) {        Instant start = clock.instant();        boolean succeeded = false;        try {            long price = inner.priceOf(sku);            succeeded = true;            return price;        } finally {            recordQuietly(sku, Duration.between(start, clock.instant()), succeeded);        }    }     private void recordQuietly(String sku, Duration took, boolean succeeded) {        try {            log.record(sku, took, succeeded);        } catch (RuntimeException e) {            // A broken log must never change the answer, so its failure is dropped.        }    }

It reads the clock, calls the inner service, and records the time in a finally block. The finally runs whether the call returned or threw, so failures are recorded too. Then the price, or the exception, carries on to the caller unchanged.

The log itself can fail too: a full disk, a broken connection to the metrics system. recordQuietly catches that and drops it. Without it, an exception from the log would replace the price that came back, or hide the real lookup failure. A missing log line is a smaller problem than a checkout that cannot get a price.

Layers that add a job around the call follow one rule: they add work and leave the answer alone.

Decision

What is a layer allowed to change?

Anything that helps the caller, such as returning a fallback price when the service fails

A layer that catches the failure and returns the last known price, or 0, keeps the checkout page up. But the caller never learns that the price is a guess, and a page that shows a $1,299 chair for $0 is worse than a page that shows an error.

Nothing about the answer: the same price or the same exception, with extra work around itOur pick

Every layer keeps the interface's promise, so any layer can wrap any other and the caller does not need to know which are there. The cache is the one exception the requirements allow: it can return a price up to 5 minutes old. If a fallback price is ever wanted, it should be a separate, clearly named layer that the caller chooses on purpose.

Step 5: stack the layers in one place

The layers do nothing until something stacks them. One factory method does it for checkout:

layer/PriceServices.javalines 8–25 of 25
public final class PriceServices {    private static final int MAX_ATTEMPTS = 3;    private static final Duration FIRST_RETRY_WAIT = Duration.ofMillis(100);    private static final Duration MAX_RETRY_WAIT = Duration.ofSeconds(1);    private static final Duration CACHE_TIME_TO_LIVE = Duration.ofMinutes(5);     private PriceServices() {    }     // Outermost first: time what checkout waits, then the cache, then retries around the remote call.    public static PriceService forCheckout(PriceService remote, Clock clock,                                           Sleeper sleeper, CallLog log) {        PriceService retrying =                new RetryingPriceService(remote, MAX_ATTEMPTS, FIRST_RETRY_WAIT, MAX_RETRY_WAIT, sleeper);        PriceService caching = new CachingPriceService(retrying, CACHE_TIME_TO_LIVE, clock);        return new TimingPriceService(caching, clock, log);    }}

Read lines 20 to 23 from the bottom up, from the outside in. Checkout gets the timing layer. Timing wraps the cache. The cache wraps the retry layer. The retry layer wraps the remote client. A lookup travels inward through that stack and the answer travels back out.

The order is a real decision, and the compiler cannot check it, because every order type-checks. Two orders give very different results for the same lookup:

Same three layers, two orders
Both stacks look up a chair whose first remote call times out, then look it up again a minute later. On the left, our order: one log line per lookup, 180 ms for the first (two 40 ms calls and a 100 ms wait) and 0 ms for the cache hit. On the right, timing sits next to the remote call: it logs every attempt separately, never sees the 100 ms wait, and never sees the cache hit at all.Both stacks look up a chair whose first remote call times out, then look it up again a minute later. On the left, our order: one log line per lookup, 180 ms for the first (two 40 ms calls and a 100 ms wait) and 0 ms for the cache hit. On the right, timing sits next to the remote call: it logs every attempt separately, never sees the 100 ms wait, and never sees the cache hit at all.
The order decides what the log measures and whether cache hits are seen at all. Both stacks look up a chair whose first remote call times out, then look it up again a minute later. On the left, our order: one log line per lookup, 180 ms for the first (two 40 ms calls and a 100 ms wait) and 0 ms for the cache hit. On the right, timing sits next to the remote call: it logs every attempt separately, never sees the 100 ms wait, and never sees the cache hit at all.
Decision

In what order are the layers stacked?

Timing innermost, right around the remote call

The log then measures the pricing service itself, attempt by attempt. That is useful to the pricing team. But it says nothing about what checkout waited for. It misses the retry waits, and a cache hit never reaches it.

Retry outside the cache

Each retry then goes back through the cache. That works, but the cache has nothing to offer on a retry: the first attempt already missed. It only adds a map lookup to every attempt.

Timing outside, then the cache, then retry around the remote callOur pick

Timing measures exactly what checkout waits for, including cache hits and retry waits. The cache answers before any retry logic runs. Retries happen only on a real miss, closest to the call that can fail. If the pricing team also wants per-attempt numbers, a second timing layer can go inside the retry layer. Layers can repeat.

Decision

Who stacks the layers?

Each caller wraps the layers it wants by hand

This is flexible, and fine for one or two callers. But every caller must know the classes and get the order right, and the order is the part the compiler cannot check.

A factory method per kind of callerOur pick

PriceServices.forCheckout makes the order a decision made once, with a name, in one file. The admin page can get its own method with no cache. Callers that need something unusual can still stack layers by hand, because the classes are public.

The finished design

The finished design
The three layers implement PriceService, and each one also holds an inner PriceService: the loop between each layer and the interface is the whole pattern. FlakyPriceService, the demo's stand-in for the pricing service, implements PriceService too, and sits at the centre of the stack. PriceServices builds the stack for checkout. Sleeper and CallLog are interfaces, so the demo and the tests can replace real sleeping and real logging.The three layers implement PriceService, and each one also holds an inner PriceService: the loop between each layer and the interface is the whole pattern. FlakyPriceService, the demo's stand-in for the pricing service, implements PriceService too, and sits at the centre of the stack. PriceServices builds the stack for checkout. Sleeper and CallLog are interfaces, so the demo and the tests can replace real sleeping and real logging.
Every layer is a PriceService that holds a PriceService. The three layers implement PriceService, and each one also holds an inner PriceService: the loop between each layer and the interface is the whole pattern. FlakyPriceService, the demo's stand-in for the pricing service, implements PriceService too, and sits at the centre of the stack. PriceServices builds the stack for checkout. Sleeper and CallLog are interfaces, so the demo and the tests can replace real sleeping and real logging.

Here is the first lookup from the demo, traced through the stack:

A lookup that times out once
Checkout asks the timing layer for CHAIR-01, and timing starts its clock (1). The cache has no price, so it asks the retry layer (2). The first remote call times out, and the retry layer waits 100 ms (3). It calls again, and the price comes back (4). On the way out, the cache stores it (5) and timing records 180 ms (6).Checkout asks the timing layer for CHAIR-01, and timing starts its clock (1). The cache has no price, so it asks the retry layer (2). The first remote call times out, and the retry layer waits 100 ms (3). It calls again, and the price comes back (4). On the way out, the cache stores it (5) and timing records 180 ms (6).
The call travels in through every layer, and the answer travels back out. Checkout asks the timing layer for CHAIR-01, and timing starts its clock (1). The cache has no price, so it asks the retry layer (2). The first remote call times out, and the retry layer waits 100 ms (3). It calls again, and the price comes back (4). On the way out, the cache stores it (5) and timing records 180 ms (6).

The whole project is below. Click any class name in the code to open that class.

layerPriceServices.java
package layer; import java.time.Clock;import java.time.Duration; import price.PriceService; public final class PriceServices {    private static final int MAX_ATTEMPTS = 3;    private static final Duration FIRST_RETRY_WAIT = Duration.ofMillis(100);    private static final Duration MAX_RETRY_WAIT = Duration.ofSeconds(1);    private static final Duration CACHE_TIME_TO_LIVE = Duration.ofMinutes(5);     private PriceServices() {    }     // Outermost first: time what checkout waits, then the cache, then retries around the remote call.    public static PriceService forCheckout(PriceService remote, Clock clock,                                           Sleeper sleeper, CallLog log) {        PriceService retrying =                new RetryingPriceService(remote, MAX_ATTEMPTS, FIRST_RETRY_WAIT, MAX_RETRY_WAIT, sleeper);        PriceService caching = new CachingPriceService(retrying, CACHE_TIME_TO_LIVE, clock);        return new TimingPriceService(caching, clock, log);    }}
Click a class name in the code to open its fileJava · 25 lines · 362 in the project

The demo in demo/Main.java sends five lookups through the checkout stack. A fake pricing service takes 40 ms per call, and can be told to time out:

$ java demo.Main
1. CHAIR-01, the service times out once
    remote: CHAIR-01 -> timed out
    retry:  wait 100 ms
    remote: CHAIR-01 -> $1299.00
    log:    CHAIR-01 took 180 ms, ok
    price:  $1299.00
2. CHAIR-01 again, a minute later
    log:    CHAIR-01 took 0 ms, ok
    price:  $1299.00
3. CHAIR-01 when the cached price is exactly 5 minutes old
    remote: CHAIR-01 -> $1299.00
    log:    CHAIR-01 took 40 ms, ok
    price:  $1299.00
4. DESK-99, which does not exist
    remote: DESK-99 -> no such product
    log:    DESK-99 took 40 ms, failed
    error:  No product DESK-99
5. LAMP-07, the service is down
    remote: LAMP-07 -> timed out
    retry:  wait 100 ms
    remote: LAMP-07 -> timed out
    retry:  wait 200 ms
    remote: LAMP-07 -> timed out
    log:    LAMP-07 took 420 ms, failed
    error:  Could not get the price of LAMP-07: timed out

Follow the five steps. In step 1 the first call times out, the retry layer waits 100 ms, and the second call returns the price. The log records 180 ms: two calls and one wait. In step 2, a minute later, the cache answers. No remote call happens, and the log records 0 ms. In step 3 the cached price is exactly 5 minutes old, so it counts as expired and the service is called again. In step 4 the product does not exist, and the service is asked only once. In step 5 the service times out three times, the waits grow from 100 to 200 ms, and the caller gets the timeout error after 420 ms.

What it costs

The pattern makes one kind of change cheap and another expensive.

Adding a layer is cheap. A rate limit is one new class that implements PriceService, plus one line in the factory method. No existing layer changes.

Adding a method to the interface is expensive. Suppose checkout also needs pricesOf(List<String> skus), to price a whole cart in one call. Each layer must think again about what it means: does the cache answer some SKUs and fetch the rest, does a retry repeat the whole batch? A default method on the interface, one that loops over priceOf, looks like a shortcut but is a trap. A layer that inherits it calls its own priceOf once per SKU, so the real batch call in the inner service is never reached. A cart of 30 items still makes up to 30 calls to the pricing service, one for each SKU the cache does not hold.

Which change is cheap
Adding a rate limit (left) is one new class, tagged new, and one changed line in the factory. Adding pricesOf (right) changes the interface and every class that implements it: the three layers and the fake pricing service. Changed classes have an amber outline and a note on what changes. Each layer has to decide what a batch means for it.Adding a rate limit (left) is one new class, tagged new, and one changed line in the factory. Adding pricesOf (right) changes the interface and every class that implements it: the three layers and the fake pricing service. Changed classes have an amber outline and a note on what changes. Each layer has to decide what a batch means for it.
A new layer is one class. A new method touches every layer. Adding a rate limit (left) is one new class, tagged new, and one changed line in the factory. Adding pricesOf (right) changes the interface and every class that implements it: the three layers and the fake pricing service. Changed classes have an amber outline and a note on what changes. Each layer has to decide what a batch means for it.

There are smaller costs too:

  • There are many small objects. A stack trace goes through every layer, and "where did this come from?" means walking the stack.
  • The order is invisible to the compiler. Every order compiles, and a wrong one shows up only as wrong numbers. Naming the order in one factory method is the defence.
  • The caller holds a wrapper, not the real object. A check like prices instanceof FlakyPriceService is false once anything wraps it. Code that checks the real class should not sit behind decorators.

When a plain method is enough

If there is one caller, it wants one fixed mix, and nothing suggests that will change, the first version is fine. Decorators pay off when different callers want different mixes, or when the jobs are reused across services.

Java also has a lighter form. A single-method interface can be decorated with a lambda, so a small layer does not need a class at all:

Sketchnot part of the final code
static PriceService logged(PriceService inner) {    return sku -> {        System.out.println("looking up " + sku);        return inner.priceOf(sku);    };} PriceService prices = logged(remote);

This is the same pattern without a named class. It works well for one-line jobs. Once a layer has settings or state, like the cache's map, a class is easier to read and test.

Decorator or Proxy?

The two are easy to confuse, because the class diagrams look the same: a class implements an interface and holds another object of that interface. The difference is in why the wrapper exists.

DecoratorProxy
Why it existsTo add a job: retries, timing, bufferingTo stand in for the real object or control access to it: a remote stub, lazy loading, a permission check
Where the inner object comes fromPassed in by whoever builds the stackOften created or found by the proxy itself
How manySeveral, stacked in an order chosen where they are builtUsually one per job: access, lazy loading or a remote call
Who chooses itWhoever builds the stack, by choosing which layers to useOften fixed: the caller may not know a proxy is there

A short way to say it: a decorator adds something to an object, and a proxy controls the way to it. The line is blurry in practice. Our cache could fairly be called a caching proxy. In an interview, if you say why your wrapper exists, the name follows.

In an interview

Decorators appear inside many low-level design questions. A discount engine stacks offers on a bill, and a repository or API client gets logging and metrics. A file system gets permission checks. Java's own streams work this way: a BufferedInputStream wraps any InputStream and adds a buffer. Web middleware also wraps each request, though it is usually described as a chain; the Chain of Responsibility page compares the two.

A good order for presenting it:

  1. Name the jobs that wrap the main call, and point out that callers want different mixes. That is the reason for the pattern, and it rules out the subclass answer.
  2. Write the interface first, then one layer in full, showing the inner field and the call to inner.
  3. Show the stacking in one place, and say out loud why the order is what it is.

Common mistakes:

  • A layer that creates its own inner object, calling new on the real client inside the layer. It can then wrap only that one class, and the layers no longer stack.
  • Swallowing exceptions in a layer. A timing or logging layer that catches an exception to record it, and forgets to throw it again, turns failures into silent wrong answers.
  • Calling the inner service twice, for example once in a log line and once for the result. Every layer below then does its work twice.
  • Retrying everything, including errors that will never succeed.
  • A subclass per combination instead of layers. It grows as two to the power of the number of jobs.
  • Ignoring the order, or leaving each caller to get it right on their own.

Summary

  • Use the Decorator pattern when several optional jobs wrap the same call, and different callers want different mixes or orders of them.
  • Every layer implements the interface it wraps, holds one inner object, does one job, and calls the inner object for the answer.
  • A layer adds work around the answer. It never changes the answer, except where the requirements allow it, like a cache's 5 minutes.
  • The order of the layers is a design decision the compiler cannot check, so make it once, in one named place.
  • Adding a layer is cheap. Adding a method to the interface touches every layer.
  • A Proxy has the same shape, but exists to stand in for an object or control access to it.

Spot a mistake, or something unclear? . Or get in touch.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.