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

Decorator Pattern: Adding Responsibilities Dynamically

Learn how Decorator attaches additional responsibilities to objects dynamically without modifying their structure.

Decorator Pattern: Adding Responsibilities Dynamically

You'll learn how to add new behavior to objects at runtime without altering their original structure.

The Core Idea

The Decorator Pattern wraps an object with another object that adds extra functionality, like wrapping a gift in decorative paper. Instead of modifying a class or creating a massive inheritance hierarchy for every feature combination, you attach responsibilities to individual objects dynamically at runtime.

Think of ordering coffee: you start with a base coffee object, then "decorate" it with milk, sugar, whipped cream, etc. Each decorator adds cost and functionality without changing the core coffee class.

Why Use Decorators?

Traditional inheritance forces you to create a new subclass for every combination: CoffeeWithMilk, CoffeeWithMilkAndSugar, CoffeeWithSugarAndWhippedCream—exponential explosion! Decorators let you compose behaviors flexibly: wrap a Coffee with a MilkDecorator, then wrap that with a SugarDecorator.

The Pattern Structure

  1. Component interface: defines operations both base objects and decorators implement
  2. Concrete component: the original object being decorated
  3. Base decorator: holds a reference to a component and forwards requests to it
  4. Concrete decorators: extend the base decorator, adding behavior before/after forwarding

Each decorator wraps the previous object, forming a chain. When you call a method, it passes through all decorators, each adding its twist.

When to Use It

Use the Decorator Pattern when you need to add responsibilities to individual objects dynamically and transparently, without affecting other objects. Perfect for scenarios requiring flexible combinations of features.

Key Takeaway: The Decorator Pattern attaches additional responsibilities to objects dynamically by wrapping them in decorator objects, providing a flexible alternative to subclassing for extending functionality.