Course contentsShow
← Computer Science
Lesson 2282 of 2,87251. Design PatternsFree lesson

Decorator vs Inheritance: Flexible Extension

Contrast Decorator pattern with inheritance to see how composition enables more flexible runtime behavior extension.

Decorator vs Inheritance: Flexible Extension

You'll learn why the Decorator pattern often beats inheritance when you need flexible, runtime behavior extension.

The Inheritance Trap

When you want to add functionality to a class, inheritance seems like the obvious choice—just create a subclass and override methods. But this approach creates static relationships at compile time. Want a coffee with milk? Create a CoffeeWithMilk subclass. Now want milk and sugar? You need CoffeeWithMilkAndSugar. The explosion of subclasses becomes unmanageable fast.

The Decorator Advantage

The Decorator pattern uses composition over inheritance. Instead of locking behavior into a class hierarchy, you wrap objects at runtime. Each decorator adds one responsibility and forwards requests to the wrapped object.

Key Differences

Inheritance:

  • Fixed at compile time
  • All subclasses inherit the same behavior
  • Deep hierarchies become rigid and fragile
  • Can't mix and match features easily

Decorator:

  • Flexible at runtime
  • Stack multiple decorators in any order
  • Each decorator focuses on one concern
  • Easy to add/remove features without changing existing code

The Coffee Analogy

With inheritance, you'd need separate classes: Coffee, CoffeeWithMilk, CoffeeWithSugar, CoffeeWithMilkAndSugar, etc.

With decorators, you compose at runtime: wrap a Coffee with a MilkDecorator, then wrap that with a SugarDecorator. Same interface, infinite combinations.

When to Use Each

Use inheritance for "is-a" relationships that won't change (a Dog is an Animal). Use Decorator when you need to add responsibilities dynamically or combine features in various ways.

Key Takeaway: Decorator provides runtime flexibility through composition, avoiding the rigid, combinatorial explosion of inheritance-based extension.