Patterns you already useeasy0-2 years

You're handed `new GzipOutputStream(new BufferedOutputStream(new FileOutputStream(path)))` in a code review with no comments. What pattern is this, how do you recognise it on sight, and what would adding "encrypted" as a fourth option cost under this design versus under a subclassing design?

It's decorator: each constructor wraps the next one, each layer adds exactly one behaviour without changing the interface, and every layer is still the same type (an OutputStream) so code that writes to it never needs to know how many layers deep it goes. The tell to look for is a constructor whose parameter is the same interface the class itself implements — new X(anotherX) — because that shape only makes sense when X is adding one thing on top of whatever it was handed. Adding "encrypted" here is one more decorator class and one more line in the wrapping expression — buffered, gzipped, encrypted is three decorators, one wrapping call. Under subclassing, the same four options (buffered, gzipped, encrypted, and combinations of them) would need a class per combination, which is why decorator exists in the first place: it turns a combinatorial explosion of subclasses into a linear stack of wrappers.

The lesson behind it →