Skip to content
BBaskaran

Facade

Provide a simple interface to a complex subsystem.

Use it when

Clients only need a small, straightforward slice of a large API.

/**
 * Facade: one simple placeOrder() call in front of several subsystems.
 *
 * Real-world scenario: an online shop. Placing an order means checking stock,
 * charging the card, booking a courier and emailing the customer, in the right
 * order. The website shouldn't have to know all four services, so a facade
 * offers a single method and coordinates them behind the scenes.
 */

// Subsystems: each does one job and knows nothing about the others.
class Inventory {
  private readonly stock = new Map([
    ["keyboard", 3],
    ["monitor", 0],
  ]);

  reserve(item: string): boolean {
    const count = this.stock.get(item) ?? 0;
    if (count === 0) {
      return false;
    }
    this.stock.set(item, count - 1);
    return true;
  }
}

class Payments {
  charge(card: string, amount: number): void {
    console.log(`  Payments: charged $${amount.toFixed(2)} to card ending ${card.slice(-4)}`);
  }
}

class Shipping {
  bookCourier(item: string, address: string): string {
    console.log(`  Shipping: courier booked for ${item} to ${address}`);
    return "TRACK-555";
  }
}

class Email {
  send(to: string, text: string): void {
    console.log(`  Email to ${to}: ${text}`);
  }
}

// Facade: the only class the website talks to.
class OrderFacade {
  private readonly inventory = new Inventory();
  private readonly payments = new Payments();
  private readonly shipping = new Shipping();
  private readonly email = new Email();

  placeOrder(item: string, price: number, card: string, customer: string): boolean {
    if (!this.inventory.reserve(item)) {
      console.log(`  Sorry, ${item} is out of stock`);
      return false;
    }
    this.payments.charge(card, price);
    const tracking = this.shipping.bookCourier(item, `${customer}'s address`);
    this.email.send(customer, `Your ${item} is on its way (${tracking})`);
    return true;
  }
}

function clientCode(): void {
  const shop = new OrderFacade();

  console.log("Order 1:");
  shop.placeOrder("keyboard", 49.99, "4111111111111111", "asha");

  console.log("Order 2:");
  shop.placeOrder("monitor", 199.0, "4111111111111111", "ravi");
}

clientCode();

// Output:
// Order 1:
//   Payments: charged $49.99 to card ending 1111
//   Shipping: courier booked for keyboard to asha's address
//   Email to asha: Your keyboard is on its way (TRACK-555)
// Order 2:
//   Sorry, monitor is out of stock

How it works

RoleClassesWhat it does
SubsystemsInventory, Payments, Shipping, EmailEach does one job and knows nothing about the others
FacadeOrderFacadeOne placeOrder(...) method that runs the steps in the right order
ClientclientCode()Talks only to the facade