Skip to content
BBaskaran

Decorator

Attach new behaviour to an object dynamically by wrapping it.

Use it when

You need to add responsibilities at runtime without subclassing.

/**
 * Decorator: add extras to a coffee order by wrapping it, one layer at a time.
 *
 * Real-world scenario: a coffee shop app. A customer can add milk, an extra shot
 * or caramel, in any combination and any number. Instead of a subclass for every
 * combination (LatteWithCaramel, LatteWithShotAndCaramel...), each extra wraps
 * the drink and adds its own cost and description.
 *
 * Note: this is the design pattern, not TypeScript's @decorator syntax (which
 * annotates classes and methods). They share the idea of wrapping, but they are
 * different things.
 */

// Component: what every drink, plain or with extras, can tell you.
interface Coffee {
  cost(): number;
  description(): string;
}

// Concrete component: the plain drink.
class Espresso implements Coffee {
  cost(): number {
    return 2.0;
  }

  description(): string {
    return "Espresso";
  }
}

// Decorator: is a Coffee and wraps a Coffee, passing calls through.
abstract class CoffeeExtra implements Coffee {
  protected readonly coffee: Coffee;

  constructor(coffee: Coffee) {
    this.coffee = coffee;
  }

  cost(): number {
    return this.coffee.cost();
  }

  description(): string {
    return this.coffee.description();
  }
}

// Concrete decorators: each adds its own cost and name on top.
class Milk extends CoffeeExtra {
  cost(): number {
    return super.cost() + 0.5;
  }

  description(): string {
    return `${super.description()} + milk`;
  }
}

class ExtraShot extends CoffeeExtra {
  cost(): number {
    return super.cost() + 0.8;
  }

  description(): string {
    return `${super.description()} + extra shot`;
  }
}

class Caramel extends CoffeeExtra {
  cost(): number {
    return super.cost() + 0.6;
  }

  description(): string {
    return `${super.description()} + caramel`;
  }
}

function printOrder(coffee: Coffee): void {
  // Client code can't tell a plain drink from a wrapped one.
  console.log(`${coffee.description()}: $${coffee.cost().toFixed(2)}`);
}

function clientCode(): void {
  printOrder(new Espresso());
  printOrder(new Milk(new Espresso()));
  printOrder(new Caramel(new ExtraShot(new Milk(new Espresso()))));
  printOrder(new Milk(new Milk(new Espresso()))); // the same extra twice works too
}

clientCode();

// Output:
// Espresso: $2.00
// Espresso + milk: $2.50
// Espresso + milk + extra shot + caramel: $3.90
// Espresso + milk + milk: $3.00

How it works

RoleClassesWhat it does
ComponentCoffeeShared interface: cost() and description()
Concrete componentEspressoThe plain drink
DecoratorCoffeeExtraAbstract class that is a Coffee, wraps a Coffee and passes calls through
Concrete decoratorsMilk, ExtraShot, CaramelEach adds its own price and name on top
ClientprintOrder()Can't tell a plain drink from a wrapped one