Facade Pattern

A Facade is one class that gives callers a small, task-shaped API over a subsystem of many collaborating classes. The subsystem keeps its structure; the Facade just means nobody outside has to learn it.

Why this matters: every machine-coding problem ends up with a cluster of classes — a request queue, a dispatcher, a state machine, a few strategies. The interviewer’s next question is “so how does a caller actually use this?” If the answer is six lines of wiring, the design has no front door. A Facade is the front door, and it is why Demo.java in a good submission reads like a story instead of like assembly.


Prerequisites


The Problem: the caller becomes the integrator

Here is an elevator bank without a Facade. The caller has to know every collaborator, the order they run in, and what to do when one of them says no:

// Caller code -- the pressButton handler in some UI class
RequestValidator validator = new RequestValidator(floorCount);
if (!validator.isServiceable(from, to)) return;

Request request = new Request(from, to, Direction.of(from, to));
DispatchStrategy strategy = new NearestCarStrategy();
Elevator chosen = strategy.select(elevators, request);
if (chosen == null) {
    pendingQueue.add(request);          // easy to forget
    return;
}
chosen.getStopList().insert(from);      // reaching two levels in
chosen.getStopList().insert(to);
chosen.setState(ElevatorState.MOVING);  // and mutating state directly
auditLog.record(request, chosen.getId());

Three things are wrong, and all three are things interviewers mark down:

  1. The knowledge leaked. Every caller now knows that dispatch can return nothing and that a pending queue exists. Add a second caller and the rule gets copy-pasted — and the copy will forget the queue.
  2. chosen.getStopList().insert(...) reaches through one object to mutate another. That is a Law of Demeter violation, and it means Elevator cannot change how it stores stops without breaking the UI.
  3. There is no single place to add a rule. “Don’t dispatch to an elevator in maintenance” has to be added to every call site.

Class Diagram

classDiagram
    class ElevatorSystem {
        -List~Elevator~ elevators
        -DispatchStrategy strategy
        -Queue~Request~ pending
        +requestRide(from, to) RideTicket
        +step()
        +status() SystemStatus
    }
    class RequestValidator {
        +isServiceable(from, to) boolean
    }
    class DispatchStrategy {
        <<interface>>
        +select(elevators, request) Elevator
    }
    class Elevator {
        -int id
        -ElevatorState state
        +addStop(int floor)
        +move()
    }
    class AuditLog {
        +record(request, elevatorId)
    }

    ElevatorSystem --> RequestValidator
    ElevatorSystem --> DispatchStrategy
    ElevatorSystem --> Elevator
    ElevatorSystem --> AuditLog

ElevatorSystem is the Facade. Note what the arrows do not show: nothing points back from a subsystem class to the Facade, and no caller arrow reaches past it. The subsystem classes stay public and independently testable — a Facade is an extra door, not a wall.


Real-World Example: Elevator Bank

// The Facade: one class, three verbs, no subsystem types in the signatures
public class ElevatorSystem {

    private final List<Elevator> elevators;
    private final DispatchStrategy strategy;
    private final RequestValidator validator;
    private final AuditLog auditLog;
    private final Deque<Request> pending = new ArrayDeque<>();

    public ElevatorSystem(int elevatorCount, int floorCount, DispatchStrategy strategy) {
        this.elevators = IntStream.rangeClosed(1, elevatorCount)
                                  .mapToObj(Elevator::new)
                                  .collect(Collectors.toList());
        this.strategy = strategy;
        this.validator = new RequestValidator(floorCount);
        this.auditLog = new AuditLog();
    }

    /**
     * The whole point of the class. A caller passes two floor numbers and gets
     * back a ticket; everything in between is this method's problem.
     */
    public RideTicket requestRide(int from, int to) {
        if (!validator.isServiceable(from, to)) {
            throw new UnserviceableFloorException(from, to);
        }
        Request request = new Request(from, to);

        Optional<Elevator> chosen = strategy.select(available(), request);
        if (chosen.isEmpty()) {
            pending.addLast(request);              // the rule lives here, once
            return RideTicket.queued(request.getId());
        }

        Elevator elevator = chosen.get();
        elevator.addStop(from);                    // Elevator owns its stop list
        elevator.addStop(to);
        auditLog.record(request, elevator.getId());
        return RideTicket.assigned(request.getId(), elevator.getId());
    }

    /** One tick of the simulation. Drains the pending queue as cars free up. */
    public void step() {
        elevators.forEach(Elevator::move);
        while (!pending.isEmpty()) {
            Request next = pending.peekFirst();
            Optional<Elevator> chosen = strategy.select(available(), next);
            if (chosen.isEmpty()) break;           // still nothing free, stop draining
            pending.removeFirst();
            chosen.get().addStop(next.getFrom());
            chosen.get().addStop(next.getTo());
        }
    }

    public SystemStatus status() {
        return new SystemStatus(
            elevators.stream().map(Elevator::snapshot).collect(Collectors.toList()),
            pending.size());
    }

    private List<Elevator> available() {
        return elevators.stream()
                        .filter(e -> e.getState() != ElevatorState.MAINTENANCE)
                        .collect(Collectors.toList());
    }
}

// Caller code now -- this is the part that gets graded
ElevatorSystem system = new ElevatorSystem(4, 20, new NearestCarStrategy());
RideTicket ticket = system.requestRide(3, 17);
system.step();
from collections import deque
from typing import Optional

class ElevatorSystem:
    """Facade over validator + dispatch strategy + elevators + audit log."""

    def __init__(self, elevator_count: int, floor_count: int,
                 strategy: 'DispatchStrategy') -> None:
        self._elevators = [Elevator(i) for i in range(1, elevator_count + 1)]
        self._strategy = strategy
        self._validator = RequestValidator(floor_count)
        self._audit = AuditLog()
        self._pending: deque['Request'] = deque()

    def request_ride(self, from_floor: int, to_floor: int) -> 'RideTicket':
        if not self._validator.is_serviceable(from_floor, to_floor):
            raise UnserviceableFloorError(from_floor, to_floor)

        request = Request(from_floor, to_floor)
        chosen = self._strategy.select(self._available(), request)
        if chosen is None:
            self._pending.append(request)
            return RideTicket.queued(request.id)

        chosen.add_stop(from_floor)
        chosen.add_stop(to_floor)
        self._audit.record(request, chosen.id)
        return RideTicket.assigned(request.id, chosen.id)

    def step(self) -> None:
        for elevator in self._elevators:
            elevator.move()
        while self._pending:
            nxt = self._pending[0]
            chosen = self._strategy.select(self._available(), nxt)
            if chosen is None:
                break
            self._pending.popleft()
            chosen.add_stop(nxt.from_floor)
            chosen.add_stop(nxt.to_floor)

    def status(self) -> 'SystemStatus':
        return SystemStatus([e.snapshot() for e in self._elevators],
                            len(self._pending))

    def _available(self) -> list['Elevator']:
        return [e for e in self._elevators
                if e.state is not ElevatorState.MAINTENANCE]
#include <deque>
#include <memory>
#include <optional>
#include <vector>

class ElevatorSystem {
    std::vector<std::shared_ptr<Elevator>> elevators_;
    std::shared_ptr<DispatchStrategy> strategy_;
    RequestValidator validator_;
    AuditLog audit_;
    std::deque<Request> pending_;

    std::vector<std::shared_ptr<Elevator>> available() const {
        std::vector<std::shared_ptr<Elevator>> out;
        for (const auto& e : elevators_)
            if (e->getState() != ElevatorState::MAINTENANCE) out.push_back(e);
        return out;
    }

public:
    ElevatorSystem(int elevatorCount, int floorCount,
                   std::shared_ptr<DispatchStrategy> strategy)
        : strategy_(std::move(strategy)), validator_(floorCount) {
        for (int i = 1; i <= elevatorCount; ++i)
            elevators_.push_back(std::make_shared<Elevator>(i));
    }

    RideTicket requestRide(int from, int to) {
        if (!validator_.isServiceable(from, to))
            throw UnserviceableFloorException(from, to);

        Request request(from, to);
        auto chosen = strategy_->select(available(), request);
        if (!chosen) {
            pending_.push_back(request);
            return RideTicket::queued(request.getId());
        }
        (*chosen)->addStop(from);
        (*chosen)->addStop(to);
        audit_.record(request, (*chosen)->getId());
        return RideTicket::assigned(request.getId(), (*chosen)->getId());
    }

    void step() {
        for (auto& e : elevators_) e->move();
        while (!pending_.empty()) {
            const Request& next = pending_.front();
            auto chosen = strategy_->select(available(), next);
            if (!chosen) break;
            (*chosen)->addStop(next.getFrom());
            (*chosen)->addStop(next.getTo());
            pending_.pop_front();
        }
    }
};

The one rule that keeps a Facade honest

No subsystem type may appear in a Facade’s signatures. requestRide(int, int) returns a RideTicket, not an Elevator. The moment a method hands back a live subsystem object, callers start reaching through it and you are back to chosen.getStopList().insert(...).

This is also the test for whether you have written a Facade or just a shortcut class. Scan the public methods: if the parameter and return types are all requests, tickets, snapshots and primitives, it is a Facade. If Elevator, DispatchStrategy and Request are in there, it is a thin wrapper that has not actually hidden anything.

💡 status() returns a SystemStatus of immutable snapshots rather than the List<Elevator> itself, for the same reason. Handing out the live list lets a caller mutate the subsystem behind the Facade’s back. Learn more →


Facade vs Adapter vs Mediator vs Service Layer

These four get confused in interviews more than any other group, because all four are “a class in the middle”. The difference is what each one is in the middle of:

Pattern Intent Interface it exposes Tell
Facade Simplify access to a subsystem you own A new, smaller one of your own design Callers had to do multi-step wiring; now they do one call
Adapter Make an incompatible class fit an interface you already have An interface that already existed You cannot change the thing you are wrapping
Mediator Stop N peers from referencing each other Peers talk to it, not through it The peers were in an N×N mesh
Service Layer Hold a use case’s transaction and authorization boundary Application-level operations It is where @Transactional and the permission check go

The practical overlap: in a layered codebase the Service Layer class usually is the Facade, which is why InventoryManagement tags both. That is fine. What matters in an interview is that you can say which job the class is doing when asked.


When to Use vs When to Avoid

Use Facade When Avoid When
A use case spans three or more collaborators The subsystem is already one class
Callers keep repeating the same wiring sequence Each caller legitimately needs a different subset
You want one place for cross-cutting rules (audit, validation) It would only forward calls one-to-one with no added rule
The subsystem’s internals are still in flux You would have to expose subsystem types anyway to be useful
A demo or main() should read as a narrative Hiding the structure is the thing being graded (a parser, say)

The failure mode has a name: a god facade. It starts as three methods, every new feature adds one, and two months later it is a 40-method class that is the only way to touch anything. The guard is that a Facade gets methods for use cases, not for subsystem operations — requestRide earns a method, setElevatorState does not.


Interview Questions

  1. “Does a Facade have to be the only way in?” – No, and saying it must be is the common mistake. GoF is explicit that the subsystem stays accessible. A power user who needs NearestCarStrategy directly can still have it; the Facade exists so the other 95% of callers do not have to. If you do need to forbid direct access, that is enforced by module visibility (package-private classes, Java modules), not by the pattern.

  2. “Facade vs Adapter?” – Intent and ownership. Adapter converts an interface you do not control into one your code already expects, so the target interface is fixed and pre-existing. Facade invents a new, simpler interface over classes you do own. A one-method Facade and an Adapter can look identical in code; the question “did I design this interface, or did I have to match someone else’s?” separates them.

  3. “Where do transactions and retries go — Facade or subsystem?” – The Facade, because it is the only object that knows the use case boundary. The subsystem classes each do one step and cannot know whether step three failing should roll back step one. This is exactly why the Service Layer and the Facade usually collapse into one class.

  4. “How do you test a Facade?” – Inject the subsystem rather than constructing it, then the Facade’s own tests use fakes and assert on orchestration: that an empty dispatch result enqueues the request, that an unserviceable floor throws before anything mutates. The constructor above builds its own collaborators for brevity, which is the version you write at minute 70 of a machine-coding round; the testable version takes them as parameters. Dependency Injection covers the trade-off.

  5. “Is a REST controller a Facade?” – Usually not. A controller translates a protocol (HTTP, JSON) into method calls, which makes it closer to an Adapter. If your controller contains the orchestration — validate, dispatch, enqueue, audit — the Facade is missing and the controller has absorbed it, which is the bug “fat controller” names.


See It in Action

  • Elevator System – ElevatorSystem fronts dispatch, cars and the pending queue
  • Multilevel Cache – one get/put API over L1, L2 and the backing store
  • Splitwise – an expense service over split strategies and the balance sheet
  • Inventory Management – the service layer and the Facade are the same class