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

The Decorator Pattern for Behavior Layering

Wrap objects with decorator functions that add behavior dynamically without modifying the original object.

The Decorator Pattern for Behavior Layering

You'll learn how to wrap objects with decorator functions that add new behaviors dynamically without altering the original object.

What Is the Decorator Pattern?

The decorator pattern lets you "wrap" an object or function with additional functionality. Think of it like gift wrapping: the present inside stays unchanged, but you add layers around it. Each decorator layer enhances or modifies behavior while keeping the core object intact.

Unlike inheritance, which bakes behavior into a class hierarchy, decorators are applied at runtime and can be stacked in any combination.

How It Works

You create a function that takes an object, adds new behavior (often by wrapping existing methods), and returns an enhanced version:

function withLogging(obj) {
  return {
    ...obj,
    execute() {
      console.log('Executing...');
      return obj.execute();
    }
  };
}

function withTimestamp(obj) {
  return {
    ...obj,
    execute() {
      const result = obj.execute();
      console.log(`Done at ${new Date().toISOString()}`);
      return result;
    }
  };
}

const task = {
  execute() {
    return 'Task complete';
  }
};

const enhanced = withTimestamp(withLogging(task));
enhanced.execute();
// Logs: Executing...
// Logs: Done at 2024-...
// Returns: 'Task complete'

Each decorator wraps the previous object, calling through to the original execute method while adding its own layer of behavior.

Why Use Decorators?

  • Flexibility: Add features on-demand without modifying the original object
  • Composability: Stack multiple decorators in different orders
  • Open/Closed Principle: Extend behavior without changing existing code

Key Takeaway: The decorator pattern wraps objects with functions that add behavior dynamically, enabling flexible composition without inheritance or mutation of the original object.