Design Patterns

Pattern 10 of 23, Structural family

Facade

Provide a simplified interface to a complex set of classes, libraries or subsystems.

The problem

Placing an order involves inventory, payment, shipping and email. Every controller rewrites this orchestration and depends on 4 different services.

The solution

Create an OrderFacade class that exposes one simple method (placeOrder()) and internally orchestrates the subsystems in the right order.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. A single call on the client side.
  2. The facade orchestrates the subsystem in the right orderโ€ฆ
  3. OrderFacade โ†’ Payment: charge()
  4. OrderFacade โ†’ Shipping: schedule()
  5. OrderFacade โ†’ Mailer: sendConfirmation()
  6. The client gets the result without knowing about the 4 services.

An analogy

A shop's phone switchboard: a single call, and the operator coordinates inventory, payment and shipping for you.

When to use it

  • Simplifying the use of a complex subsystem
  • Defining entry points per layer (application services)
  • Reducing the client code's dependencies

Pros and cons

Pros

  • Client decoupled from internal details
  • Centralized, reusable orchestration

Cons

  • Risk of a "god object" that keeps growing
  • Can hide useful advanced features

Implementations

The same example, written idiomatically in each language.

Facade in Python

facade.py 27 lines
class Inventory:
    def reserve(self, items): print("stock reserved")

class Payment:
    def charge(self, amount): print(f"paid {amount} DT")

class Shipping:
    def schedule(self, address): return "TRK-42"

class Mailer:
    def send(self, to, body): print(f"mail -> {to}")


class OrderFacade:
    def __init__(self):
        self.inventory, self.payment = Inventory(), Payment()
        self.shipping, self.mailer = Shipping(), Mailer()

    def place_order(self, cart, total, address, email) -> str:
        self.inventory.reserve(cart)
        self.payment.charge(total)
        tracking = self.shipping.schedule(address)
        self.mailer.send(email, f"Order shipped: {tracking}")
        return tracking


OrderFacade().place_order(["book"], 59, "Tunis", "client@mail.tn")

Facade in TypeScript

facade.ts 21 lines
class Inventory { reserve(items: string[]) { /* โ€ฆ */ } }
class Payment { async charge(amount: number) { /* โ€ฆ */ } }
class Shipping { schedule(address: string) { return "TRK-42"; } }
class Mailer { async send(to: string, body: string) { /* โ€ฆ */ } }

export class OrderFacade {
  constructor(
    private inventory = new Inventory(),
    private payment = new Payment(),
    private shipping = new Shipping(),
    private mailer = new Mailer(),
  ) {}

  async placeOrder(cart: string[], total: number, address: string, email: string) {
    this.inventory.reserve(cart);
    await this.payment.charge(total);
    const tracking = this.shipping.schedule(address);
    await this.mailer.send(email, "Order shipped: " + tracking);
    return tracking;
  }
}

Facade in Java

facade.java 18 lines
public class OrderFacade {
    private final Inventory inventory;
    private final Payment payment;
    private final Shipping shipping;
    private final Mailer mailer;

    public OrderFacade(Inventory i, Payment p, Shipping s, Mailer m) {
        inventory = i; payment = p; shipping = s; mailer = m;
    }

    public String placeOrder(List<String> cart, BigDecimal total, String address, String email) {
        inventory.reserve(cart);
        payment.charge(total);
        String tracking = shipping.schedule(address);
        mailer.send(email, "Order shipped: " + tracking);
        return tracking;
    }
}

Facade in C#

facade.cs 12 lines
public class OrderFacade(Inventory inventory, Payment payment, Shipping shipping, Mailer mailer)
{
    public async Task<string> PlaceOrderAsync(
        IEnumerable<string> cart, decimal total, string address, string email)
    {
        inventory.Reserve(cart);
        await payment.ChargeAsync(total);
        var tracking = shipping.Schedule(address);
        await mailer.SendAsync(email, $"Order shipped: {tracking}");
        return tracking;
    }
}

Facade in PHP

facade.php 22 lines
final class OrderFacade
{
    public function __construct(
        private Inventory $inventory,
        private Payment $payment,
        private Shipping $shipping,
        private Mailer $mailer,
    ) {}

    public function placeOrder(array $cart, float $total, string $address, string $email): string
    {
        $this->inventory->reserve($cart);
        $this->payment->charge($total);
        $tracking = $this->shipping->schedule($address);
        $this->mailer->send($email, "Order shipped: $tracking");

        return $tracking;
    }
}

// Note: Laravel "Facades" (Cache::get) are really static proxies to the
// service container, but the intent of simplification is the same.

Facade in Go

facade.go 22 lines
type OrderFacade struct {
    inv  *Inventory
    pay  *Payment
    ship *Shipping
    mail *Mailer
}

func NewOrderFacade() *OrderFacade {
    return &OrderFacade{&Inventory{}, &Payment{}, &Shipping{}, &Mailer{}}
}

func (f *OrderFacade) PlaceOrder(cart []string, total float64, addr, email string) (string, error) {
    if err := f.inv.Reserve(cart); err != nil {
        return "", err
    }
    if err := f.pay.Charge(total); err != nil {
        return "", err
    }
    trk := f.ship.Schedule(addr)
    f.mail.Send(email, "Order shipped: "+trk)
    return trk, nil
}

Frequently asked questions

What is the Facade design pattern?

Provide a simplified interface to a complex set of classes, libraries or subsystems. Create an OrderFacade class that exposes one simple method (placeOrder()) and internally orchestrates the subsystems in the right order.

When should you use the Facade pattern?

Simplifying the use of a complex subsystem; Defining entry points per layer (application services); Reducing the client code's dependencies.

What are the pros and cons of the Facade pattern?

Pros: Client decoupled from internal details; Centralized, reusable orchestration. Cons: Risk of a "god object" that keeps growing; Can hide useful advanced features.