Decorator

Adds behaviour to an object by wrapping it in another object with the same interface, without changing the original class.

Why it matters

You want to add extras like logging, caching or retries to some objects, in different combinations, without writing a subclass for every combination.

The idea

Instead of a subclass for every combination (LoggedCachedRetryingClient and so on), you stack small wrappers: a retry wrapper around a cache wrapper around the real client. Each wrapper adds one feature and passes the call along.

Wrapping a present in layers: paper, then ribbon, then a card. It's still the same present underneath, and you can add or skip any layer.

Gift layers don't affect each other. Code wrappers do, so the order matters: caching outside retries behaves differently from retries outside caching.

How it works

  1. Start with an object that implements an interface: read().
  2. Write a wrapper class that implements the same interface and holds another object of that interface.
  3. In its read(), do the extra work (write a log line, check a cache), then call the inner object's read().
  4. Wrap again for more features: Logging(Caching(Real())).
  5. Callers can't tell they're talking to a wrapper; they just call read().

Example

Java's file streams (a BufferedInputStream around a FileInputStream), and Python's @decorators for logging or timing functions.

Key points

Common mistakes

Not true: The order in which decorators are stacked never changes the result.
In fact: Order matters: with the cache in the wrong place, a failure is stored and served again and again. Choose the order on purpose.

In the interview

Decorator wraps an object with another that has the same interface and adds one behaviour, like logging, caching or retries. Wrappers can be stacked in any combination, which avoids an explosion of subclasses.

Part of Unit 6: Design patterns in the free System Design course.