Course contentsShow
← JavaScript
Lesson 1847 of 2,72338. Object-Oriented PatternsFree lesson

The Decorator Pattern

Dynamically add behavior to objects by wrapping them, keeping the interface consistent.

The Decorator Pattern

You'll learn how to dynamically add behavior to objects by wrapping them while keeping their interface consistent.

What Is the Decorator Pattern?

The Decorator Pattern lets you add new functionality to an object without modifying its original structure. Instead of changing the object itself or using inheritance, you wrap it in another object that provides additional behavior while delegating the core functionality to the original.

Think of it like wrapping a gift: the present stays the same, but each layer of wrapping paper adds something new without changing what's inside.

How It Works

The decorator implements the same interface as the original object, so consumers don't know they're working with a wrapper. When a method is called, the decorator can:

  • Add behavior before delegating to the original
  • Add behavior after receiving the original's result
  • Transform the result
  • Decide whether to call the original at all

This differs from mixins (which merge properties) and the Strategy Pattern (which swaps algorithms). Decorators layer behavior dynamically at runtime.

Plain Object Example

function createLogger(component) {
  return {
    render() {
      console.log('Rendering started');
      const result = component.render();
      console.log('Rendering complete');
      return result;
    }
  };
}

const button = {
  render() { return '<button>Click</button>'; }
};

const loggedButton = createLogger(button);
loggedButton.render();
// Logs before and after, returns same HTML

Why Use Decorators?

  • Flexibility: Add features without inheritance chains
  • Single Responsibility: Each decorator handles one concern
  • Composability: Stack multiple decorators for combined effects

Key Takeaway: The Decorator Pattern wraps objects to add behavior dynamically while maintaining their interface, enabling flexible, composable enhancements without modifying original code.