Decorator
A decorator implements the same interface as the object it wraps and adds behaviour before or after forwarding. You stack decorators instead of growing subclasses.
Detailed Explanation
BufferedInputStream wraps an InputStream and still is an InputStream. GZIPInputStream wraps again. Callers see one type. Each layer does one job. That is decorator.
Inheritance would need BufferedGzipFileInputStream for every combination. Decorators compose at runtime: new MetricsMailer(new RetryMailer(new SmtpMailer())). Each implements Mailer.
A decorator keeps a reference to the wrappee (often the interface, so you can wrap a wrap). It forwards methods it does not change. It overrides the ones it enhances. Order matters: retry-outside-metrics counts attempts; metrics-outside-retry counts successes.
Java I/O streams are the textbook. Servlet filters are close. Spring's HandlerInterceptor and wrapper HttpServletRequestWrapper are the same idea.
You reach for a decorator when you want optional features (logging, retry, cache) without touching the core class. You reach for a proxy when the extra job is access control or lazy load and you want a stand-in that may not even construct the real object yet. You reach for subclassing when the type is closed and you own it and there is one variant.
The cost of deep stacks is long stack traces and surprising order. The cost of a decorator that changes the contract (throws new exceptions, drops methods) is a lie. Keep the interface honest. Identity (==) breaks: the decorator is not the wrappee. equals should usually not unwrap.
java.lang.reflect.Proxy can generate a decorator at runtime. Hand-written classes are easier to debug.
A good decorator has one reason to exist: retry, metrics, or a prefix. When a decorator both retries and logs and caches, you cannot turn one feature off. Stack three thin wrappers instead. The object graph at main or in the Spring config becomes the feature list, which is easier to read than a 200-line wrapper.
Code Examples
interface Mailer {
void send(String to, String body);
}
class SmtpMailer implements Mailer {
@Override
public void send(String to, String body) {
System.out.println(to + ":" + body);
}
}
class PrefixMailer implements Mailer {
private final Mailer inner;
PrefixMailer(Mailer inner) {
this.inner = inner;
}
@Override
public void send(String to, String body) {
inner.send(to, "[app] " + body);
}
public static void main(String[] args) {
Mailer mailer = new PrefixMailer(new SmtpMailer());
mailer.send("a@b.com", "hi"); // prints: a@b.com:[app] hi
}
}Common Gotchas
Decorator order is behaviour
document which layer is outermost.
`==` and some `instanceof` checks see the wrapper, not the core
`==` and some `instanceof` checks see the wrapper, not the core