Part 4 of 6 · 3 min read
Facade
One simple door to many classes.
Think of a hotel front desk. A guest who wants a room, a cab and a wake-up call does not call housekeeping, the taxi firm and the switchboard. The guest asks the desk, and the desk talks to each.
GoF's intent for Facade is to put one simple front over the many interfaces of a subsystem, so it is easier to use. GoF's applicability list covers three cases: you want an easy default view of a complex subsystem, clients depend on many implementation classes directly, or you want to layer subsystems with one entry point per layer.
A booking needs several services: availability, pricing, payment and notification. A client that called all four would need to know the order, the failure cases and the rules.
class BookingFacade {
private final Availability av; private final Pricing pr;
private final Payments pay; private final Notifier n;
BookingFacade(Availability av, Pricing pr, Payments pay, Notifier n) {
this.av = av; this.pr = pr; this.pay = pay; this.n = n;
}
String bookAndPay(String user, String room, int hour, int hours) {
if (!av.isFree(room, hour)) return "room busy";
long cost = pr.price(room, hours);
if (!pay.charge(user, cost)) return "payment failed";
av.hold(room, hour);
n.send(user, "booked " + room);
return "booked for " + cost;
}
}
With a price of 500 per hour (made up), bookAndPay("asha", "A1", 9, 2) returns "booked for 1000" and sends one message. A second call for the same room and hour returns "room busy" and charges nothing. The client makes one call, and the steps and their order live in one place.
GoF lists the benefits. A facade shields clients from the subsystem's parts, so they deal with fewer objects. It promotes weak coupling, so the subsystem can change without affecting clients. And it does not stop clients from using subsystem classes directly when they need to, so there is a choice between ease of use and generality.
HF connects this to the principle of least knowledge (Level 2, module 6). A client that talks to one facade knows about one class, not four. The facade also helps with SRP, since the order of steps is the facade's single job and the services stay simple.
Facade pattern
The Facade pattern is a single class that gives a simple interface to a group of classes, and passes each request on to the right ones.
Example: BookingFacade.bookAndPay, which calls availability, pricing, payment and notification.
Common mistake
Putting business rules in the facade. It should only coordinate. A facade that grows rules becomes a god class (Level 2, module 1), and the rules should live in the subsystem classes.
Check yourself:
1. What does the second call to bookAndPay for the same slot return?
2. Why does a facade not stop direct use of the subsystem?
3. What should a facade not contain?