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

Implementing Decorator: Wrappers and Forwarding

Understand how decorators maintain the same interface while delegating to wrapped components.

Implementing Decorator: Wrappers and Forwarding

What you'll learn: How decorators wrap objects while maintaining the same interface and delegating behavior.

The Core Mechanism

A decorator works by wrapping an existing component and passing through (forwarding) method calls to it, optionally adding behavior before or after. The crucial insight: the decorator implements the same interface as the component it wraps, so clients can't tell the difference.

Think of it like gift wrapping a present. The wrapped gift still is a gift—you can give it, open it, and use what's inside. The wrapper just adds something extra (decoration, protection) while maintaining the essential "gift" interface.

How Forwarding Works

The decorator holds a reference to the wrapped component. When a method is called on the decorator, it:

  1. Receives the call (because it implements the same interface)
  2. Optionally adds behavior before the call
  3. Forwards the call to the wrapped component
  4. Optionally adds behavior after the call
  5. Returns the result to the caller

This forwarding is what makes decorators transparent—they don't replace functionality, they enhance it.

The Pattern in Plain Terms

Imagine a coffee shop interface with a getCost() method. A plain coffee implements this interface. A "milk decorator" also implements the coffee interface, wraps the plain coffee, and when asked for cost, it forwards to the wrapped coffee's cost and adds milk's cost. A "whipped cream decorator" can then wrap the milk decorator the same way. Each wrapper maintains the coffee interface while delegating the core work down the chain.

This delegation chain is what allows decorators to stack—each maintains the interface contract while adding its layer of behavior.

Key Takeaway: Decorators maintain interface compatibility by wrapping components and forwarding method calls, allowing transparent behavior enhancement through composition rather than inheritance.