Simple definition#
The Facade pattern provides one simple interface to a set of classes that together form a subsystem. Clients call the facade; the facade knows which subsystem objects to call and in what order.
GoF intent: “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.”
The problem#
Placing an order involves four services: reserve stock, charge the card, schedule shipping and send a confirmation. If payment fails, the stock reservation must be released.
If every caller (the web controller, the mobile API, the batch re-order job) coordinates these four services itself:
- the sequence and the compensation logic are duplicated and drift apart
- each caller depends on four classes and their details
- changing the subsystem (adding fraud checks) means changing every caller.
Real-world analogy#
A hotel concierge. You say “book me dinner and a taxi for 8 pm”. The concierge calls the restaurant, the taxi company and updates your bill. You could do it yourself, but you do not need to know the phone numbers.
Structure#
- Facade (
CheckoutFacade) — knows which subsystem classes handle a request and delegates. - Subsystem classes (
InventoryService,PaymentService,ShippingService,NotificationService) — do the work; have no reference to the facade. - Client — calls the facade.
classDiagram
direction LR
class Client
class CheckoutFacade {
+placeOrder(customerId, sku, qty, unitPrice) String
}
class InventoryService {
+reserve(sku, qty) String
+release(reservationId)
}
class PaymentService {
+charge(customerId, amount) String
}
class ShippingService {
+schedule(customerId, reservationId) String
}
class NotificationService {
+orderConfirmed(customerId, shipmentId)
}
Client --> CheckoutFacade
CheckoutFacade --> InventoryService
CheckoutFacade --> PaymentService
CheckoutFacade --> ShippingService
CheckoutFacade --> NotificationServiceJava implementation#
The code is in examples/java/src/hub/patterns/facade/FacadeDemo.java.
/** Subsystem classes: each is useful on its own and knows nothing about the facade. */
final class InventoryService {
private final Map<String, Integer> stock = new HashMap<>(Map.of("SKU-1", 5, "SKU-2", 0));
String reserve(String sku, int qty) {
int available = stock.getOrDefault(sku, 0);
if (available < qty) {
throw new IllegalStateException("only " + available + " of " + sku + " in stock");
}
stock.put(sku, available - qty);
System.out.println(" inventory: reserved " + qty + " x " + sku);
return "RES-" + sku;
}
void release(String reservationId) {
System.out.println(" inventory: released " + reservationId);
}
}
final class PaymentService {
String charge(String customerId, BigDecimal amount) {
if (amount.compareTo(new BigDecimal("1000")) > 0) {
throw new IllegalStateException("card declined");
}
System.out.println(" payment: charged " + amount + " to " + customerId);
return "PAY-" + customerId;
}
}
final class ShippingService {
String schedule(String customerId, String reservationId) {
System.out.println(" shipping: scheduled " + reservationId + " for " + customerId);
return "SHP-1";
}
}
final class NotificationService {
void orderConfirmed(String customerId, String shipmentId) {
System.out.println(" notify: order confirmed for " + customerId + ", shipment " + shipmentId);
}
}/** Facade: one simple operation that hides the order and the compensation logic of the subsystem calls. */
final class CheckoutFacade {
private final InventoryService inventory;
private final PaymentService payments;
private final ShippingService shipping;
private final NotificationService notifications;
CheckoutFacade(InventoryService inventory, PaymentService payments,
ShippingService shipping, NotificationService notifications) {
this.inventory = inventory;
this.payments = payments;
this.shipping = shipping;
this.notifications = notifications;
}
String placeOrder(String customerId, String sku, int qty, BigDecimal unitPrice) {
String reservation = inventory.reserve(sku, qty);
try {
payments.charge(customerId, unitPrice.multiply(BigDecimal.valueOf(qty)));
} catch (RuntimeException e) {
inventory.release(reservation); // compensate: callers never have to remember
return "FAILED (" + e.getMessage() + ")";
}
String shipment = shipping.schedule(customerId, reservation);
notifications.orderConfirmed(customerId, shipment);
return "CONFIRMED";
}
}Order 1:
inventory: reserved 2 x SKU-1
payment: charged 99.00 to C-7
shipping: scheduled RES-SKU-1 for C-7
notify: order confirmed for C-7, shipment SHP-1
=> CONFIRMED
Order 2:
inventory: reserved 3 x SKU-1
inventory: released RES-SKU-1
=> FAILED (card declined)The second order exceeds the card limit. The facade releases the reservation, so no caller can forget to compensate.
Step-by-step walkthrough#
- Identify a use case that requires several subsystem calls in a fixed order: “place an order”.
- Write one method for it on the facade, expressed in the client’s vocabulary.
- Put coordination and compensation inside, so the subsystem’s protocol is encoded once.
- Leave the subsystem accessible. A facade is a convenience, not a wall: advanced clients may still call
InventoryServicedirectly.
Facade and the Principle of Least Knowledge#
Head First pairs Facade with the Principle of Least Knowledge (the Law of Demeter): talk only to your immediate friends. A method should call methods on itself, its parameters, objects it creates and its fields, not on objects returned by other calls.
// Violates it: the client reaches through three objects
order.getCustomer().getAccount().getWallet().debit(amount);
// Follows it: ask the nearest object to do the work
order.chargeCustomer(amount);
A facade gives clients one “immediate friend” instead of a web of subsystem objects. See OO design principles.
Facade versus similar patterns#
| Pattern | Purpose | Direction of knowledge |
|---|---|---|
| Facade | Simplify a subsystem for clients | Facade knows the subsystem; subsystem does not know the facade |
| Adapter | Make one existing interface match another | Adapter wraps usually one object and changes its interface |
| Mediator | Coordinate peers that would otherwise talk to each other | Colleagues know the mediator and send it events |
| API gateway | A facade at the network edge for many microservices | Same idea, at the architecture level |
In layered and hexagonal architectures, an application service (a use-case class) is usually a facade over the domain and the outbound ports.
Advantages and disadvantages#
| Advantages | Disadvantages |
|---|---|
| Simple entry point for common use cases | Can grow into a “god object” that knows everything |
| Clients are decoupled from subsystem details | Adds a layer; trivial pass-through facades are noise |
| Coordination and compensation are written once | Advanced features may be hidden, tempting people to bypass it |
| Subsystem can change behind a stable interface | — |
When to use it#
- A subsystem is complex and most clients need only a few common operations.
- You want to layer a system: each layer exposes a facade to the one above.
- Wrapping a legacy or third-party library behind a small, intention-revealing API.
When not to use it#
- The subsystem is already simple.
- You need to change an interface for compatibility: use an Adapter.
- The facade would just forward each method one-to-one.
Common mistakes#
- One facade per subsystem class, which adds layers without simplifying anything.
- Hiding the subsystem completely, forcing every new need through the facade.
- Facades that return subsystem internals, re-exposing the complexity they were meant to hide.
Real-world uses#
javax.faces.context.FacesContextandjava.net.URL.openStream()hide multi-step protocols.- SLF4J’s
LoggerFactoryis a facade over logging back ends (and a Bridge, see Bridge). - Spring’s
JdbcTemplate,RestClientandKafkaTemplatepresent a simple API over connection management, resource cleanup and exception translation. - Application services in Hexagonal Architecture.
Interview questions and answers#
What is the Facade pattern? A structural pattern that provides a single, simplified interface to a complex subsystem of classes.
How is Facade different from Adapter? Adapter makes an existing interface match one a client expects. Facade defines a new, simpler interface over many classes.
Does a facade prevent access to the subsystem? No. It is a convenience; clients that need more control can still use the subsystem classes directly.
Which principle does Facade support? The Principle of Least Knowledge (Law of Demeter): clients talk to one immediate friend instead of reaching through many objects.
Summary#
- Facade gives a subsystem one simple, use-case-oriented entry point.
- It encodes call order and compensation once.
- Keep it thin; business rules belong elsewhere.
- API gateways and application services are facades at larger scales.
Related topics#
- Adapter vs Decorator vs Proxy vs Facade
- Mediator Pattern
- API Gateway with Spring Cloud Gateway
- OO design principles
References#
- Gamma, Helm, Johnson, Vlissides. Design Patterns. Addison-Wesley, 1994. Facade, p. 185.
- Eric Freeman, Elisabeth Robson. Head First Design Patterns (2nd edition). O’Reilly, 2020. Chapter 7 (home theater facade, Principle of Least Knowledge).