Course contentsShow
← Software Engineering
Lesson 271 of 1,9338. Structural Design PatternsFree lesson

Decorator vs. Inheritance: Flexibility and Complexity

Compare Decorator's runtime composition with inheritance, understanding when each approach is appropriate.

Decorator vs. Inheritance: Flexibility and Complexity

What you'll learn: You'll understand when to use runtime composition (Decorator) versus compile-time inheritance to extend functionality.

The Core Difference

Inheritance creates fixed relationships at compile time. When you create a BoldText subclass of Text, that relationship is permanent. Decorators, on the other hand, let you compose behavior at runtime—you can wrap objects in different combinations whenever you need them.

When Inheritance Works Well

Use inheritance when:

  • You have a true "is-a" relationship
  • The hierarchy is stable and won't change often
  • You need a small, predictable set of combinations

Example: A Dog is an Animal. This relationship rarely changes.

When Decorator Shines

Use Decorator when:

  • You need many possible combinations of features
  • Behavior must change at runtime
  • You want to avoid an explosion of subclasses

Analogy: Think of coffee orders. Inheritance would require separate classes for every combination: CoffeeWithMilk, CoffeeWithMilkAndSugar, CoffeeWithMilkAndSugarAndWhippedCream, etc. With Decorator, you wrap: WhippedCream(Sugar(Milk(Coffee()))).

The Complexity Trade-off

Inheritance is simpler to understand—the class hierarchy is explicit. But it's rigid: changing requirements means creating new subclasses or refactoring.

Decorator is more flexible—infinite combinations without new classes. But it's complex: you're creating wrapper chains that can be harder to debug and understand.

Making the Choice

Ask yourself: "Will I know all possible combinations at design time?" If yes, inheritance might suffice. If you need flexibility or many combinations, reach for Decorator.

Key Takeaway: Decorator trades some conceptual simplicity for runtime flexibility, avoiding the class explosion that inheritance causes when you need many feature combinations.