How does the GoF Decorator pattern differ from inheritance for adding behavior?
Options
- It is identical to inheritance in how it adds new behavior
- It wraps an object with the same interface, so behaviors stack (Correct option)
- It requires multiple inheritance to combine the behaviors
- It modifies the original class directly at compile time
Answer
It wraps an object with the same interface at runtime, so behaviors can be stacked dynamically
Why
The Decorator pattern wraps an object in another object that has the SAME interface and adds one extra behavior (logging, caching, retries).
Because wrappers look identical from outside, you can stack them in any combination at runtime: Cached(Logged(SqlRepo())).
With inheritance you would need a subclass for every combination.
Remember
Decorator pattern = wrap and add, same interface.