You’re reading a file. It’s gzip-compressed on disk, so you need to decompress it. It’s also large, so you want buffered reads. Next quarter it’ll be encrypted at rest, and someone will ask for a running checksum. Each of those is a small, orthogonal responsibility layered onto “read bytes from a file.”
Try to model that with inheritance and you get a name that reads like a ransom note: BufferedEncryptedGzipChecksummingFileInputStream. Four features, and the number of subclasses you’d need to cover every combination is 2⁴ − 1 = 15. Add a fifth feature and it’s 31. The features are independent, but subclassing forces you to pre-enumerate every product of them at compile time — a combinatorial explosion for behavior that the caller wants to mix and match at runtime.
The features don’t want to be classes. They want to be layers. That’s the pattern the Gang of Four named.
The intuition: Russian dolls that all look the same from outside
Think of a wrapped gift, or a set of Russian nesting dolls. Each layer sits around the one beneath it and adds something — a ribbon, a coat of paint — but from the outside every layer presents the same surface: it’s still a doll, still something you can open. You can nest three or thirty; the thing you hold always behaves like a single doll.
A decorator is exactly that. Each layer wraps the object below it, shares the object’s interface so it’s indistinguishable from the outside, and adds a little behavior before or after passing the call inward. The innermost doll is the real object doing the base work; every layer around it is a responsibility bolted on at runtime.
The members-only continuation builds the whole thing out: the four-role structure and UML, the interface-plus-two-decorators code you can trace one write and one read through, the Decorator-vs-Proxy distinction, the java.io and Servlet API cases in the wild, the composition-vs-inheritance tradeoffs, and an interview corner that refactors a notification-service subclass explosion — with a quiz to check yourself.
Keep reading with Premium
You've reached the members-only part of this deep-dive — the full implementation, the interactive ring simulator, and the step-by-step walkthrough. Unlock it with a membership.
Discussion
Loading the conversation…
Discussion
Loading the conversation…