Repaso
Español
Design & PracticesAdvancedDP-13

How does the GoF Decorator pattern differ from inheritance for adding behavior?

Options

  1. It is identical to inheritance in how it adds new behavior
  2. It wraps an object with the same interface, so behaviors stack (Correct option)
  3. It requires multiple inheritance to combine the behaviors
  4. 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.

Key terms

Practice this question in Repaso