Loading
Loading
Patterns Worth Knowing
Adapter, Decorator, Facade, Composite and Proxy — four ways to put something in front of something else, and one way to treat a group as one.
By the end of this chapter
| Pattern | Interface of the wrapper | Adds | Reason to exist |
|---|---|---|---|
| Adapter | Different from the wrapped | Nothing | Two incompatible interfaces must meet |
| Decorator | Same as the wrapped | Behaviour | Optional behaviour, stackable |
| Proxy | Same as the wrapped | Control | Lazy loading, access checks, caching |
Adapter is the one with a different interface on each side — it exists precisely because the two do not fit. Decorator and Proxy both keep the interface identical, so they can be inserted invisibly; they differ in whether they are adding capability or governing access.
LogSink sink = new TimestampSink( new LevelFilterSink(WARN, new FileSink(path)));The property that makes this work is that every wrapper implements the same one-method interface, so they stack in any combination. Try this with a six-method interface and each decorator must forward five methods it does not care about — which is Interface Segregation showing up as a practical constraint.
**Problem.** A caller wants to treat one thing and a group of things identically.
**Shape.** The group implements the same interface as the individual and forwards to its children. A CompositeSink that holds three sinks *is* a sink; nothing above it knows or cares.
**When it does not fit.** When the interface has methods a group cannot sensibly answer. A group has no single `getName()`, and inventing one is the design telling you Composite is wrong here.
**Problem.** A subsystem has many parts and a caller needs one common workflow through them.
**Shape.** One class exposing the workflow, delegating inward. **The risk.** A facade that accumulates a method per caller becomes exactly the god object it was meant to hide — with the additional problem that it is now the only documented way in. Keep it to the genuinely common paths and let unusual callers reach the parts directly.
Sign in to keep a note here. It is free, and nobody else can see it.
Sign inWhat this chapter was for: