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

Decorator Pattern: Adding Behavior Dynamically

Learn how Decorator wraps objects to add responsibilities at runtime without modifying their class.

Decorator Pattern: Adding Behavior Dynamically

You'll learn how the Decorator pattern lets you add new responsibilities to objects at runtime without changing their underlying classes.

The Core Idea

Imagine ordering a plain coffee. You can add milk, then sugar, then whipped cream—each addition wraps the previous drink, adding something new without changing what coffee fundamentally is. The Decorator pattern works the same way: it wraps an object inside another object that adds extra behavior, and you can keep wrapping to add more features.

Unlike inheritance, where you decide behaviors at compile-time and must create separate classes for every combination (MilkCoffee, SugarCoffee, MilkSugarCoffee...), Decorator composes behaviors at runtime. Each decorator implements the same interface as the object it wraps, so from the outside, it looks identical.

How It Works

The decorator has-a (composition) relationship with the object it decorates and is-a (inheritance/interface) relationship with the same type. When a method is called, the decorator can:

  1. Add behavior before delegating to the wrapped object
  2. Delegate to the wrapped object, then add behavior after
  3. Do both, surrounding the call with additional logic

This creates chains: WhippedCreamDecorator(SugarDecorator(MilkDecorator(PlainCoffee))). Each layer adds its contribution transparently.

Why Use Decorator?

The pattern follows the Open/Closed Principle—objects are open for extension but closed for modification. You add features by wrapping, not editing existing code. It also avoids the class explosion problem of inheritance-based approaches and lets clients mix-and-match features dynamically.

Key Takeaway: The Decorator pattern wraps objects in layers that add responsibilities at runtime, using composition and a shared interface to extend behavior without modifying original classes.