SyntaxPilot
Courses/Low-Level Design/Lesson 30
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 30 of 90

Facade pattern

Facade patternsubsystemsimplified interfaceentry pointlayering with facadesfacade vs adapterfacade vs mediatorhome-theatre or checkout example

These are the notes for Low-Level Design (LLD) episode 30, the fourth structural pattern. The Adapter changed an interface, the Decorator added behaviour, and the Proxy controlled access, each around one object. The Facade wraps a whole group of classes and gives them one simple front door. We start with ordering through a waiter, then watch Priya's website team copy a five-step checkout, lose one line, and charge a customer for food that is out of stock. Then we invent the facade, see how facades build layers, compare Facade vs Adapter and Facade vs Mediator, and avoid the god facade. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.

1. The real-life idea: ordering through a waiter

At a restaurant In code
Kitchen, store room, billing counter, delivery staff The subsystem: a group of classes that work together on one job
You, the customer, just want a masala dosa The client: code that needs the job done
The waiter: one sentence, and he handles the rest in the right order The facade: one simple method in front of the subsystem
The kitchen door isn't locked; a regular can still ask the chef Not a cage: subsystem classes can still be used directly

The word facade (say "fa-saad") means the front face of a building: what you see from the street, hiding the rooms behind it.

2. The problem: five classes, in the right order

Placing one order needs five subsystem classes:

Class Job
Inventory reserve(dish): take one from stock, or return false if none are left
Coupons apply(code, rs): CHAI10 takes Rs 10 off
Payments charge(user, rs)
Delivery assign(dish): find a rider
Sms send(user, text): a text message

The mobile app calls them in the right order: reserve first, stop if out of stock, then charge, assign, send. The website team copies the code and loses the reserve line. Paneer tikka has 0 in stock:

import java.util.*;

class Inventory { Map<String, Integer> stock = new HashMap<>(Map.of("dosa", 5, "paneer tikka", 0));
    boolean reserve(String d) { return stock.get(d) > 0 && stock.merge(d, -1, Integer::sum) >= 0; }
}
class Coupons  { int apply(String code, int rs) { return code.equals("CHAI10") ? rs - 10 : rs; } }
class Payments { void charge(String u, int rs) { System.out.println("  paid Rs " + rs + " by " + u); } }
class Delivery { void assign(String dish) { System.out.println("  rider assigned for " + dish); } }
class Sms      { void send(String u, String text) { System.out.println("  SMS to " + u + ": " + text); } }

public class Main {
    static Inventory inv = new Inventory();  static Coupons cp = new Coupons();
    static Payments pay = new Payments();  static Delivery del = new Delivery();  static Sms sms = new Sms();

    static void appCheckout(String user, String dish, int rs, String code) {   // the mobile app
        if (!inv.reserve(dish)) { System.out.println("  sorry, " + dish + " is out of stock"); return; }
        pay.charge(user, cp.apply(code, rs));
        del.assign(dish);
        sms.send(user, "order placed");
    }
    static void webCheckout(String user, String dish, int rs, String code) {   // copied for the website
        pay.charge(user, cp.apply(code, rs));                                   // forgot reserve()
        del.assign(dish);
        sms.send(user, "order placed");
    }
    public static void main(String[] args) {
        System.out.println("app:");      appCheckout("asha", "paneer tikka", 240, "CHAI10");
        System.out.println("website:");  webCheckout("ravi", "paneer tikka", 240, "CHAI10");
    }
}
app:
  sorry, paneer tikka is out of stock
website:
  paid Rs 230 by ravi
  rider assigned for paneer tikka
  SMS to ravi: order placed

No error, no exception: Ravi paid Rs 230 and got a rider for a dish that doesn't exist.

(stock.merge(d, -1, Integer::sum) adds −1 to the dish's count; Integer::sum is a method reference, episode 5. && stops early, so merge only runs when stock is above 0.)

Why it failed

  • Every client must know five classes and the exact order to call them in.
  • That knowledge was copied; copies drift (get out of sync) and forget steps.
  • Changing the steps (add loyalty points) means editing every client.
  • We want one place that knows the steps, and one simple call for every client.

3. The fix: a facade

import java.util.*;

class Inventory { Map<String, Integer> stock = new HashMap<>(Map.of("dosa", 5, "paneer tikka", 0));
    boolean reserve(String d) { return stock.get(d) > 0 && stock.merge(d, -1, Integer::sum) >= 0; }
}
class Coupons  { int apply(String code, int rs) { return code.equals("CHAI10") ? rs - 10 : rs; } }
class Payments { void charge(String u, int rs) { System.out.println("  paid Rs " + rs + " by " + u); } }
class Delivery { void assign(String dish) { System.out.println("  rider assigned for " + dish); } }
class Sms      { void send(String u, String text) { System.out.println("  SMS to " + u + ": " + text); } }
class OrderFacade {                                          // one simple front door
    private final Inventory inv = new Inventory();  private final Coupons cp = new Coupons();
    private final Payments pay = new Payments();  private final Delivery del = new Delivery();
    private final Sms sms = new Sms();
    String placeOrder(String user, String dish, int rs, String code) {
        if (!inv.reserve(dish)) return "  sorry, " + dish + " is out of stock";  // check first
        pay.charge(user, cp.apply(code, rs));
        del.assign(dish);
        sms.send(user, "order placed");
        return "  done";
    }
}
public class Main {
    public static void main(String[] args) {
        OrderFacade shop = new OrderFacade();
        System.out.println("app:");
        System.out.println(shop.placeOrder("asha", "dosa", 240, "CHAI10"));
        System.out.println("website:");
        System.out.println(shop.placeOrder("ravi", "paneer tikka", 240, "CHAI10"));
    }
}
app:
  paid Rs 230 by asha
  rider assigned for dosa
  SMS to asha: order placed
  done
website:
  sorry, paneer tikka is out of stock

OrderFacade holds the five subsystem objects privately and has one method, placeOrder, with the steps written once, in the right order: check stock before any payment. Both screens make one call. The website can't forget a step any more, because it doesn't know the steps.

A method that is the single place where a job begins is called an entry point.

4. It has a name: the Facade pattern

Intent (SourceMaking, Facade): "Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use." In short: "Wrap a complicated subsystem with a simpler interface."

Role Meaning In our code
Facade Knows which subsystem classes to call, and in what order; offers a simple method OrderFacade.placeOrder
Subsystem classes Do the real work; don't know the facade exists Inventory, Coupons, Payments, Delivery, Sms
Clients Make one call to the facade the app, the website, a future kiosk

Dependencies point one way: clients → facade → subsystem. Nothing in the subsystem refers back to the facade.

A facade is not a cage: the subsystem classes stay public, so a refund screen can still call Payments directly. The facade makes the common path easy; it doesn't forbid the rest.

5. Layering with facades

A layer is a group of classes at one level of a system. A typical shape:

Layer Contains Talks to
UI layer app screens, website pages, kiosk facades only
Service layer OrderFacade, AccountFacade, RefundFacade subsystem classes
Subsystems inventory, payments, delivery, SMS databases, external APIs

Rule: each layer talks only to the layer just below it, and a facade is that layer's front door. Benefits:

  • Switching to a new payment company changes only code below the facade; the screens don't notice.
  • The checkout order is tested once, by giving OrderFacade fake subsystem objects (via the constructor, episode 16).
  • New clients (a kiosk, a WhatsApp bot) get the whole job with one call.

6. Testing the facade

Because the steps live in one place, they can be tested once. OrderFacade now receives its subsystem objects through its constructor (constructor injection, episode 16). The test uses fakes (small stand-in objects for tests), written as anonymous classes (a class with no name, written where it's used, here overriding one method) that record their calls in a list:

import java.util.*;

class Inventory { boolean reserve(String d) { return true; } }
class Payments  { void charge(String u, int rs) { } }
class Delivery  { void assign(String d) { } }
class OrderFacade {
    private final Inventory inv; private final Payments pay; private final Delivery del;
    OrderFacade(Inventory i, Payments p, Delivery d) { inv = i; pay = p; del = d; }   // injected
    String placeOrder(String user, String dish, int rs) {
        if (!inv.reserve(dish)) return "out of stock";
        pay.charge(user, rs);
        del.assign(dish);
        return "done";
    }
}
public class Main {
    public static void main(String[] args) {
        List<String> calls = new ArrayList<>();                           // fakes record their calls
        Inventory empty = new Inventory() { boolean reserve(String d) { calls.add("reserve"); return false; } };
        Payments pay = new Payments() { void charge(String u, int rs) { calls.add("charge"); } };
        Delivery del = new Delivery() { void assign(String d) { calls.add("assign"); } };
        String r = new OrderFacade(empty, pay, del).placeOrder("ravi", "paneer tikka", 240);
        System.out.println(r + ", calls = " + calls);
        System.out.println(calls.equals(List.of("reserve")) ? "TEST PASSED" : "TEST FAILED: charged first!");
    }
}
out of stock, calls = [reserve]
TEST PASSED

A teammate "tidies up" placeOrder and moves the charge above the stock check. It still compiles; the test catches it:

import java.util.*;

class Inventory { boolean reserve(String d) { return true; } }
class Payments  { void charge(String u, int rs) { } }
class Delivery  { void assign(String d) { } }
class OrderFacade {
    private final Inventory inv; private final Payments pay; private final Delivery del;
    OrderFacade(Inventory i, Payments p, Delivery d) { inv = i; pay = p; del = d; }   // injected
    String placeOrder(String user, String dish, int rs) {
        pay.charge(user, rs);                                  // "tidied up" by a teammate
        if (!inv.reserve(dish)) return "out of stock";
        del.assign(dish);
        return "done";
    }
}
public class Main {
    public static void main(String[] args) {
        List<String> calls = new ArrayList<>();                           // fakes record their calls
        Inventory empty = new Inventory() { boolean reserve(String d) { calls.add("reserve"); return false; } };
        Payments pay = new Payments() { void charge(String u, int rs) { calls.add("charge"); } };
        Delivery del = new Delivery() { void assign(String d) { calls.add("assign"); } };
        String r = new OrderFacade(empty, pay, del).placeOrder("ravi", "paneer tikka", 240);
        System.out.println(r + ", calls = " + calls);
        System.out.println(calls.equals(List.of("reserve")) ? "TEST PASSED" : "TEST FAILED: charged first!");
    }
}
out of stock, calls = [charge, reserve]
TEST FAILED: charged first!

Without the facade, every screen that copied the steps would need its own copy of this test.

7. When to use a facade (and when not)

Use a facade when Skip it when
Many clients repeat the same multi-step workflow One client makes one simple call: a facade is extra code
A complex library or SDK where most users need a few of its many classes Every client needs different steps: no common path
At layer boundaries (UI → services) You're adding it "just in case" (YAGNI, episode 17: you aren't gonna need it)

8. Facade vs Adapter

Facade Adapter (episode 27)
Wraps many objects (a subsystem) usually one object
Interface defines a new, simpler one (placeOrder didn't exist) matches one that already exists (PaymentGateway)
Purpose simplify convert

9. Facade vs Mediator

A mediator (its own episode later) is an object that a group of objects talk through, instead of talking to each other directly, like air-traffic control: planes talk to the tower, not to each other.

Facade Mediator
Direction one-way: clients → facade → subsystem two-way: colleagues ↔ mediator
Do the wrapped classes know it? No Yes, they call it
Purpose simpler entry point coordinate many peers, reduce their coupling

10. The god-facade trap

Putting every operation in the whole app into one AppFacade creates a god class (episode 12): thousands of lines, every team editing it, low cohesion (its methods don't belong together). Make one facade per job: orders, accounts, refunds. A facade should also return simple results (strings, your own small records), not subsystem objects, or clients start depending on the subsystem again.

Common mistakes

Mistake Exact message / symptom Why Fix
Every client calls the subsystem steps itself no error: paid Rs 230 by ravi for an out-of-stock dish A copied sequence forgot reserve() One facade method owns the steps
Charging before checking stock no error: rider assigned for paneer tikka Steps in the wrong order Check first, then pay, inside the facade
One facade for the whole app no error: a 3,000-line class God class, low cohesion One facade per job
Facade returns subsystem objects no error: clients import Payments again The subsystem leaks through Return simple results
Business rules spread between facade and clients no error: discounts applied twice Two places own one rule Keep the workflow in the facade, the rules in the subsystem

Mini project: a TripPlanner facade

Booking a trip needs Train.book(from, to), Hotel.reserve(city, nights) (returns false when the city is full), Cab.call(city) and Sms.send(text). Write TripPlanner.book(from, to, nights) that books the train only if the hotel is available, and test a Delhi → Jaipur trip and a Delhi → Goa trip when Goa is full.

Solution
import java.util.*;

class Train { void book(String from, String to) { System.out.println("  train " + from + " -> " + to + " booked"); } }
class Hotel {
    private final Set<String> full = Set.of("Goa");
    boolean reserve(String city, int nights) {
        if (full.contains(city)) return false;
        System.out.println("  hotel in " + city + " for " + nights + " nights"); return true;
    }
}
class Cab { void call(String city) { System.out.println("  cab waiting at " + city + " station"); } }
class Sms { void send(String text) { System.out.println("  SMS: " + text); } }

class TripPlanner {                                           // the facade
    private final Train train = new Train(); private final Hotel hotel = new Hotel();
    private final Cab cab = new Cab(); private final Sms sms = new Sms();
    String book(String from, String to, int nights) {
        if (!hotel.reserve(to, nights)) return "  no rooms in " + to + ", nothing booked";
        train.book(from, to);
        cab.call(to);
        sms.send("trip to " + to + " confirmed");
        return "  done";
    }
}
public class Main {
    public static void main(String[] args) {
        TripPlanner trips = new TripPlanner();
        System.out.println("Jaipur:"); System.out.println(trips.book("Delhi", "Jaipur", 2));
        System.out.println("Goa:");    System.out.println(trips.book("Delhi", "Goa", 3));
    }
}
Jaipur:
  hotel in Jaipur for 2 nights
  train Delhi -> Jaipur booked
  cab waiting at Jaipur station
  SMS: trip to Jaipur confirmed
  done
Goa:
  no rooms in Goa, nothing booked

The client never sees four classes or their order; Goa is refused before any train is booked.

Practice

1. Add loyalty points (Loyalty.add(user, rs / 10)) after payment. How many classes change?

Answer

One: OrderFacade.placeOrder gets one new line (plus the new Loyalty class). The app, website and kiosk are untouched. Without the facade, every client would need editing.

2. Is OrderFacade an adapter? Why or why not?

Answer

No. It doesn't make one existing class fit an existing interface; it defines a new, simpler method over five classes. That's a facade.

3. How would you unit-test the order of steps in placeOrder?

Answer

Pass the five subsystem objects into OrderFacade's constructor (dependency injection, episode 16). In the test, pass fakes that append their name to a shared list, call placeOrder, and assert the list is [reserve, apply, charge, assign, send], and that an out-of-stock dish produces only [reserve].

4. The refund screen calls Payments.refund() directly instead of going through a facade. Is that wrong?

Answer

Not necessarily. A facade doesn't lock the subsystem. If refunds grow into several steps (refund, restock, SMS), give them their own RefundFacade.

5. Name the pattern: (a) one method startMovie() that dims lights, lowers the screen and starts the projector; (b) planes talk only to the tower; (c) BankSdkAdapter.

Answer

(a) Facade, (b) Mediator, (c) Adapter.

Quick quiz

// A) class Rupees implements Money { /* wraps one Dollar object */ }
// B) class TripPlanner { book() calls Train, Hotel, Cab, Sms }
// C) class LoggedPayment implements Payment { /* adds a log line */ }
// D) class ImageProxy implements Image { /* loads on first show */ }

Which one is a facade?

Answer

B. It gives one simple book() over four subsystem classes. A converts one object to another interface (adapter), C adds behaviour (decorator), D loads lazily (proxy).

Interview questions

  1. What is the Facade pattern? A structural pattern that provides a unified, higher-level interface to a set of interfaces in a subsystem, making it easier to use.
  2. Participants? Facade, subsystem classes, clients.
  3. Does the subsystem know about the facade? No. Dependencies go one way.
  4. Does a facade prevent direct access to the subsystem? No; it simplifies the common path. Clients may still use subsystem classes.
  5. Facade vs Adapter? Facade simplifies many classes with a new interface; Adapter converts one class to an existing interface.
  6. Facade vs Mediator? Facade is a one-way front door; a Mediator coordinates two-way communication between peers that know it.
  7. How do facades help layering? Each layer exposes facades to the layer above, so changes below don't ripple up.
  8. Risks? A god facade; leaking subsystem types; hiding too much so advanced clients can't do what they need.
  9. Examples? A checkout service placeOrder(), a TripPlanner.book(), a home-theatre watchMovie(), a library's main entry class over many internal ones.
  10. How do you test a facade? Inject fake subsystem objects and assert the order and stopping conditions of calls.

Glossary

Term Meaning, with an example
Facade pattern One simple front for a group of classes. OrderFacade.placeOrder()
Facade The class offering the simple method and calling the subsystem in order
Subsystem A group of classes that work together on one job. Inventory, Payments, Delivery …
Client Code that needs the job done. The app, the website
Simplified (higher-level) interface One call that stands for many lower-level calls
Entry point The single place where a job begins
Unified interface One interface in front of many
Layer / layering A group of classes at one level; each talks only to the one below
UI layer / service layer Screens / the facades and services they call
Drift Copies of the same code getting out of sync
Mediator A hub that a group of objects talk through instead of to each other
God class A class that does far too much (episode 12)
Cohesion How well a class's parts belong together (episode 10)
Adapter Converts one class's interface to an expected one (episode 27)
Dependency injection Passing the objects a class needs into it, e.g. via the constructor (episode 16)
Method reference Short form of a lambda that calls an existing method. Integer::sum
Map.merge Combine a new value with the existing one for a key. stock.merge(d, -1, Integer::sum)
Fake A small stand-in object used in tests that records or returns fixed answers
Anonymous class A class with no name, written where it's used. new Payments() { void charge(...) { ... } }
YAGNI "You aren't gonna need it": don't build what you don't need yet (episode 17)
SMS A text message to a phone
Loyalty points Points a customer earns per order

Summary

  • When every client calls many subsystem classes in a fixed order, the order gets copied, and copies drift and forget steps.
  • A facade puts the steps and their order in one method; clients make one call.
  • The subsystem doesn't know the facade, and isn't locked away.
  • Facades form layers: UI → facades → subsystems.
  • Facade simplifies; Adapter converts; Mediator is a two-way hub. Avoid the god facade: one facade per job.

Next episode: The Bridge pattern.