Why does the Decorator pattern scale better than subclassing when you have several optional, independently combinable features?
Subclassing models each combination of features as its own class, so the number of classes needed grows roughly as 2^n for n independent optional features -- with even a handful of features, that becomes impractical to write and test. Decorator instead models each feature as its own small wrapper class that implements the same interface as the thing it wraps, so any subset of features can be composed at runtime by wrapping the base object in whichever decorators are needed, in whatever order. This turns a combinatorial class explosion into a linear number of decorator classes, and it lets combinations be assembled dynamically rather than requiring every combination to be anticipated and hand-coded in advance.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response