Structural PatternsDecorator PatternEasy⏱️ ~2 min

Decorator Pattern: Definition and Core Problem

Definition
Decorator Pattern is a structural design pattern that allows adding new behaviors or responsibilities to objects dynamically by wrapping them in decorator objects, without modifying the original class or affecting other instances.
Problem It Solves:

In object-oriented design, you often need to add functionalities to objects at runtime. Traditional approaches create issues: First, using inheritance for every combination leads to a class explosion (if you have 3 features, you need 2^3 = 8 subclasses). Second, inheritance is static and decided at compile time, not runtime. Third, modifying the base class affects all subclasses violating the Open/Closed Principle (OCP).

Real-World Analogy: Think of ordering coffee. A basic espresso can be decorated with milk (latte), then whipped cream, then caramel. Each addition wraps the previous beverage without changing the espresso class itself.

Key Characteristics:

First, decorators implement the same interface as the objects they wrap, making them interchangeable. Second, decorators contain a reference to the wrapped object (composition over inheritance). Third, decorators forward requests to the wrapped object and may perform additional actions before or after forwarding. Fourth, multiple decorators can be stacked, creating a chain of responsibility.

When NOT to Use: If you only have one or two variations, simple inheritance is cleaner. If the order of decorators matters significantly and creates complex dependencies, consider the Strategy Pattern instead. If you need to remove decorators dynamically after adding them, this pattern becomes cumbersome.

💡 Key Takeaways
Adds responsibilities to objects dynamically without modifying their class
Uses composition instead of inheritance to avoid class explosion
Decorators implement the same interface as the wrapped component
Enables stacking multiple decorators for combined behaviors
Follows Open/Closed Principle: open for extension, closed for modification
📌 Examples
1Coffee shop: Adding milk, sugar, whipped cream to base beverages
2Text editor: Adding borders, scrollbars, shadows to UI components
3Stream processing: Adding buffering, compression, encryption to data streams
← Back to Decorator Pattern Overview
Decorator Pattern: Definition and Core Problem | Decorator Pattern - System Overflow