Sixteen classes for three features
A photo-sharing service stores uploads through a BlobStore interface with two methods, put(key, bytes) and get(key), and one implementation, S3BlobStore. Over a few months the team needs three extras: retry a call that failed on a network blip, record how long each call takes, and log every write. Not everywhere, though. The thumbnail job wants retries and timings but no log; the admin tool wants the log and nothing else.
Subclassing handles the first extra well enough: RetryingS3BlobStore extends S3BlobStore. The second needs TimedS3BlobStore, and also RetryingTimedS3BlobStore for the jobs that want both. Three independent extras make eight combinations, counting the plain store, and the team is about to add a second backend for on-premises customers, which doubles that to sixteen classes. Every further extra doubles the count again, and each combined class tends to repeat the code of the extras it contains.
A store that holds a store
Decorator layers behavior around an object without subclassing its class. Each extra becomes a class that implements BlobStore and holds another BlobStore inside. RetryingStore.put() calls the inner store's put() and, if that times out, calls it again, up to three attempts. TimingStore.put() starts a timer, calls the inner put() and records the elapsed time in a finally block, so a call that fails is timed too. Neither knows whether the object inside is the S3 store or another decorator, because from outside both are just a BlobStore.
The combinations now happen when objects are built, not when classes are written: new TimingStore(new RetryingStore(new S3BlobStore())) for the thumbnail job, new LoggingStore(new S3BlobStore()) for the admin tool. Three extras are three classes, and a second backend is one more class, not eight. Decorators share the component's interface, so the outermost wrapper is a drop-in replacement for the original: code that relies only on that interface cannot tell it from the plain store, and that is what lets the wrappers stack.
Each wrapper implements BlobStore and forwards to the one object inside it; the job holds only the outermost.
Adding timing changed neither S3BlobStore nor any caller: the code was extended without being edited, the open/closed principle, one of the five in SOLID design principles.
The order of the wrappers is a decision
Wrapping is not commutative. With TimingStore outside RetryingStore, it measures what the caller lived through: a put() that needed three attempts shows up as one slow call. Turn the stack around, new RetryingStore(new TimingStore(s3)), and it records every attempt separately, which is what you want when the question is how S3 itself is behaving. Both orders are legitimate; they answer different questions, and the line that assembles the stack is where that choice is made, so it deserves a comment.
Order can matter for correctness, too. A LoggingStore outside the retry writes one entry per call; inside it, one entry per attempt, and an audit log that someone reads as "one entry per upload" now has duplicates. Retrying is also only acceptable here because writing the same bytes to the same key again leaves the same object stored, as long as the bucket keeps no versions and nothing else writes that key between attempts; whether a repeated call is safe in general is the question Retry answers.
Where wrapping leaks
- Changing the interface. Having a decorator change the component's interface instead of just adding behavior means wrappers can no longer be stacked or swapped in transparently. If
RetryingStoregrows aput(key, bytes, attempts)that callers start to use, the next wrapper around it hides that method, and those callers now depend on one concrete wrapper. - Forwarding by hand. Every decorator has to pass on every method of the interface, including the ones it does not care about. When
BlobStoregainsdelete(key), a statically typed language makes each decorator add it; a dynamic one lets a decorator forget it and fail at runtime. The usual remedy is the participant the pattern itself calls Decorator: an abstract base class that holds the inner object and forwards everything by default, so each concrete decorator overrides only what it changes. A wide interface makes decorators costly either way, which is one more reason to keep it small. - Identity and type checks. The outermost object is a
TimingStore, not anS3BlobStore. Code that checks whether it holds anS3BlobStore, or compares two stores by reference, gets a different answer once wrapping starts. Code that relies only on the interface is unaffected. - A stack nobody can see. Five wrappers add their own frames to every stack trace that passes through the store, and the behaviour depends on an assembly order written somewhere else. If the same stack is built in several places, build it in one function, so the order is decided once.
Other wrappers, other intents
Proxy also keeps the interface but controls access rather than adding behaviour, Adapter wraps to change the interface, and Composite shares the interface while holding many children where a decorator holds exactly one; a request passed along handlers that may each stop it is Chain of Responsibility. Java's new BufferedInputStream(new FileInputStream(path)) is the pattern itself in a standard library, while Python's @decorator syntax only shares the name and the idea of wrapping: it replaces a function or class once, when it is defined.
Two wrappers, one interface
Open the Decorator Pattern challenge and model the store from this article, or a component of your own: a Port / Interface node for the shared interface, a Component node for the plain implementation, a Decorator node for the base wrapper, and two concrete Decorator nodes that each add one responsibility. Connect every wrapper to the interface it implements and to the one object it wraps. The check that matters: stack your two decorators and confirm the outermost still satisfies the original interface, so the client's arrow could point at any layer without anything else changing.