LOW-LEVEL DESIGN · STRUCTURAL PATTERNS · STRUCTURAL · 31 OF 48

Facade Pattern in Java: One Simple Door Over a Complex Subsystem

The Facade pattern through a food order desk: one placeOrder method over stock, wallet, kitchen, rider and SMS classes, with the undo steps kept in one place. Structure, Java 17 code, when not to use it, Facade vs Adapter and Mediator, the god object trap, SLF4J and JdbcTemplate, and where it appears in LLD interviews.

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
1 / 17

Press play to hear the narration, or step through at your own pace. The Java example is below.

Java example

One file, Java 17, 173 lines, with a small main() demo. Save it as OrderDeskDemo.java, then run javac OrderDeskDemo.java && java OrderDeskDemo.

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * Facade: OrderDesk offers one simple placeOrder() over five kitchen subsystem classes.
 * First the naive version (the caller does every step and forgets the undo), then the facade.
 */
public class OrderDeskDemo {

    // ---------- the subsystem: five focused classes, each with its own API ----------
    static final class StockLedger {
        private final Map<String, Integer> portions = new HashMap<>();

        StockLedger() {
            portions.put("paneer-wrap", 5);
            portions.put("dal-bowl", 0);
        }

        boolean reserve(String dish, int qty) {
            int left = portions.getOrDefault(dish, 0);
            if (left < qty) return false;
            portions.put(dish, left - qty);
            return true;
        }

        void putBack(String dish, int qty) { portions.merge(dish, qty, Integer::sum); }

        int left(String dish) { return portions.getOrDefault(dish, 0); }
    }

    static final class WalletGateway {
        private final Map<String, Long> balance = new HashMap<>();
        private final Map<String, String> payerOf = new HashMap<>();
        private final Map<String, Long> amountOf = new HashMap<>();
        private int nextTxn = 1;

        void topUp(String customer, long paise) { balance.merge(customer, paise, Long::sum); }

        Optional<String> charge(String customer, long paise) {
            long has = balance.getOrDefault(customer, 0L);
            if (has < paise) return Optional.empty();
            balance.put(customer, has - paise);
            String txn = "TXN-" + nextTxn++;
            payerOf.put(txn, customer);
            amountOf.put(txn, paise);
            return Optional.of(txn);
        }

        void refund(String txn) {
            String customer = payerOf.remove(txn);
            Long paise = amountOf.remove(txn);
            if (customer != null && paise != null) balance.merge(customer, paise, Long::sum);
        }

        long balance(String customer) { return balance.getOrDefault(customer, 0L); }
    }

    static final class KitchenQueue {
        private final List<String> tickets = new ArrayList<>();

        int enqueue(String dish, int qty) {
            tickets.add(qty + " x " + dish);
            return tickets.size();
        }
    }

    static final class RiderDispatch {
        private int freeRiders;

        RiderDispatch(int freeRiders) { this.freeRiders = freeRiders; }

        Optional<String> assign(String area) {
            if (freeRiders == 0) return Optional.empty();
            return Optional.of("rider-" + area + "-" + freeRiders--);
        }
    }

    static final class SmsSender {
        void send(String phone, String text) { System.out.println("    sms to " + phone + ": " + text); }
    }

    record OrderRequest(String customer, String phone, String dish, int qty, long pricePaise, String area) {
        long total() { return pricePaise * qty; }
    }

    record OrderResult(boolean accepted, String message) {}

    // ---------- the problem: every caller repeats the steps, and one copy forgets the undo ----------
    static String naiveCheckout(StockLedger stock, WalletGateway wallet, KitchenQueue kitchen,
                                RiderDispatch riders, SmsSender sms, OrderRequest r) {
        if (!stock.reserve(r.dish(), r.qty())) return "sold out";
        Optional<String> txn = wallet.charge(r.customer(), r.total());
        if (txn.isEmpty()) return "payment failed";   // bug: the stock is never put back
        Optional<String> rider = riders.assign(r.area());
        if (rider.isEmpty()) return "no rider";      // bug: the customer is never refunded
        int token = kitchen.enqueue(r.dish(), r.qty());
        sms.send(r.phone(), "Confirmed, token " + token);
        return "token " + token;
    }

    // ---------- the facade: one door, a fixed order, and the undo steps in one place ----------
    static final class OrderDesk {
        private final StockLedger stock;
        private final WalletGateway wallet;
        private final KitchenQueue kitchen;
        private final RiderDispatch riders;
        private final SmsSender sms;

        OrderDesk(StockLedger stock, WalletGateway wallet, KitchenQueue kitchen,
                  RiderDispatch riders, SmsSender sms) {
            this.stock = stock;
            this.wallet = wallet;
            this.kitchen = kitchen;
            this.riders = riders;
            this.sms = sms;
        }

        /** The only method most callers ever need. It coordinates; the rules stay in the subsystem. */
        OrderResult placeOrder(OrderRequest r) {
            if (!stock.reserve(r.dish(), r.qty())) return reject(r, "sold out");
            Optional<String> txn = wallet.charge(r.customer(), r.total());
            if (txn.isEmpty()) {
                stock.putBack(r.dish(), r.qty());
                return reject(r, "payment failed");
            }
            Optional<String> rider = riders.assign(r.area());   // find a rider before cooking
            if (rider.isEmpty()) {
                wallet.refund(txn.get());                         // undo in reverse order
                stock.putBack(r.dish(), r.qty());
                return reject(r, "no rider nearby");
            }
            int token = kitchen.enqueue(r.dish(), r.qty());
            sms.send(r.phone(), "Order confirmed. Token " + token + ", " + rider.get());
            return new OrderResult(true, "token " + token);
        }

        private OrderResult reject(OrderRequest r, String why) {
            sms.send(r.phone(), "Sorry, " + why + ". You have not been charged.");
            return new OrderResult(false, why);
        }
    }

    public static void main(String[] args) {
        OrderRequest twoWraps = new OrderRequest("cust-7", "phone-7", "paneer-wrap", 2, 18_000, "sector21");

        System.out.println("Before: the screen calls the subsystem itself (no rider free)");
        StockLedger stock0 = new StockLedger();
        WalletGateway wallet0 = new WalletGateway();
        wallet0.topUp("cust-7", 100_000);
        String r0 = naiveCheckout(stock0, wallet0, new KitchenQueue(), new RiderDispatch(0),
                new SmsSender(), twoWraps);
        System.out.println("  result: " + r0 + " | wallet " + wallet0.balance("cust-7")
                + " paise (charged, never refunded) | wraps left " + stock0.left("paneer-wrap"));

        System.out.println("After: one call to the OrderDesk facade (one rider free)");
        StockLedger stock = new StockLedger();
        WalletGateway wallet = new WalletGateway();
        wallet.topUp("cust-7", 100_000);
        OrderDesk desk = new OrderDesk(stock, wallet, new KitchenQueue(), new RiderDispatch(1),
                new SmsSender());

        System.out.println("  " + desk.placeOrder(twoWraps));
        System.out.println("  " + desk.placeOrder(
                new OrderRequest("cust-7", "phone-7", "dal-bowl", 1, 12_000, "sector21")));
        System.out.println("  " + desk.placeOrder(
                new OrderRequest("cust-7", "phone-7", "paneer-wrap", 1, 18_000, "sector21")));
        System.out.println("  wallet " + wallet.balance("cust-7") + " paise (only the first order paid)"
                + " | wraps left " + stock.left("paneer-wrap"));
    }
}

Notes

The problem

Here is the naive version. The mobile app calls the stock ledger, the wallet, rider dispatch, the kitchen queue and the SMS sender, one by one. Now copy that into the website, the kiosk and the support tool. One copy forgets to refund when no rider is free, and a customer pays for food that never comes. Every caller is tied to five classes, and a change in any of them ripples everywhere.

Every screen does this
stock.reserve(dish, qty);
txn = wallet.charge(user, total);
rider = riders.assign(area);
if (rider.isEmpty()) {
  // forgot: wallet.refund(txn)
  // forgot: stock.putBack(dish, qty)
  return "no rider";
}
kitchen.enqueue(dish, qty);
sms.send(phone, "confirmed");

The idea

The idea in one sentence: give a complicated group of classes one simple front door. The Facade pattern adds a class with a small number of easy methods, and each method runs the right steps on the classes behind it. The caller learns one method, place order. The facade knows the order of calls, the business rules and how to undo a half finished job.

Facade in plain words
  • one class with a few simple
  • methods that hide a group of
  • classes behind it
  • callers learn one method:
  • placeOrder(request)
  • the facade knows the order,
  • the rules and the undo steps

The structure

Three roles. The client is the mobile app. The facade is a class we call OrderDesk. Behind it sit the subsystem classes: StockLedger, WalletGateway, KitchenQueue, RiderDispatch and SmsSender. They do all the real work, and none of them knows the facade exists. The arrows point one way only, from the facade into the subsystem. That is what keeps each subsystem class reusable on its own.

Participants
  • client: MobileApp
  • facade: OrderDesk
  • subsystem classes:
  • StockLedger, WalletGateway,
  • KitchenQueue, RiderDispatch,
  • SmsSender
  • the subsystem classes do
  • NOT know the facade exists

Code: the facade

In code, OrderDesk is an ordinary class. It holds a reference to each subsystem object and receives them through its constructor. It does not create them itself, so in a test you can pass in fakes, like a wallet that always declines. A facade is not magic. It is plain composition with a friendly method on top.

OrderDesk fields
final class OrderDesk {
  private final StockLedger stock;
  private final WalletGateway wallet;
  private final KitchenQueue kitchen;
  private final RiderDispatch riders;
  private final SmsSender sms;

  OrderDesk(StockLedger s, WalletGateway w,
      KitchenQueue k, RiderDispatch r,
      SmsSender m) { ... }
}

Code: placeOrder

The place order method runs the steps in one fixed order. First, reserve the dish in the stock ledger. If it is sold out, stop and tell the customer. Then charge the wallet. If the charge fails, put the stock back. Each step only runs if the one before it worked, and that rule now lives in exactly one place instead of in four different screens.

placeOrder, part one
OrderResult placeOrder(OrderRequest r) {
  if (!stock.reserve(r.dish(), r.qty()))
    return reject(r, "sold out");
  Optional<String> txn =
    wallet.charge(r.customer(), r.total());
  if (txn.isEmpty()) {
    stock.putBack(r.dish(), r.qty());
    return reject(r, "payment failed");
  }
  ...

Code: undo steps

Next, find a rider before cooking, so food is never made with nobody to carry it. If no rider is free, refund the charge and put the stock back, in reverse order. Only then send the ticket to the kitchen and text the customer their token. The bug from the naive version cannot happen any more, because there is only one copy of these steps.

placeOrder, part two
  Optional<String> rider =
      riders.assign(r.area());
  if (rider.isEmpty()) {
    wallet.refund(txn.get());
    stock.putBack(r.dish(), r.qty());
    return reject(r, "no rider nearby");
  }
  int token = kitchen.enqueue(r.dish(),
      r.qty());
  sms.send(r.phone(), "token " + token);
  return new OrderResult(true, ...);

Run-through

Follow one order. The app calls place order for two paneer wraps. OrderDesk reserves two portions, charges the customer three hundred and sixty rupees, asks rider dispatch for someone in sector twenty one, puts a ticket in the kitchen queue and sends the text. The app gets back one simple result: accepted, with token one. The app made one method call. The facade made five.

Not a wall

A facade is a convenience, not a locked gate. The operations console, used by staff, still talks to the kitchen queue and rider dispatch directly, because it needs features the simple door does not offer, like moving a ticket up the queue or swapping a rider. That is fine. The facade covers the common path for most callers, and the subsystem stays fully usable for the few who need more.

When to use it

Use a facade when many callers repeat the same multi step sequence, when a subsystem is hard to learn, or when you wrap a legacy system or a third party library so the rest of your code never touches it directly. It also gives tests a single seam to fake. Skip it when there is one caller and two simple calls. Then the facade is just one more file to read.

Use it or skip it
  • use it when:
  • • many callers repeat the same
  • multi-step sequence
  • • a subsystem is hard to learn
  • • you wrap a legacy system or
  • a third-party library
  • • you want one seam for tests
  • skip it when:
  • • one caller, two simple calls

The god object trap

The big risk is the god object. Because the facade is the easy place to add code, people keep adding: discount rules, tax maths, rider scoring. A year later it has three thousand lines and every change is scary. Keep the facade thin. It should coordinate, not compute. Rules belong in the subsystem class that owns the data. If it grows, split it by use case, for example an OrderDesk and a separate RefundDesk.

Keep it thin
  • warning signs:
  • • rules that belong in a
  • subsystem class creep in
  • • one facade for every feature
  • • dozens of methods
  • fixes:
  • • coordinate, do not compute
  • • one facade per use case:
  • OrderDesk, RefundDesk

Facade vs Adapter

Facade and Adapter both wrap other code, so people mix them up. An adapter takes one existing class whose interface does not fit, and makes it match an interface your client already expects, like plugging a new payment provider into your own PaymentGateway interface. A facade usually wraps many classes and invents a new, smaller interface that did not exist before. Adapter is about fitting. Facade is about simplifying.

Facade vs Adapter
  • Adapter:
  • ONE existing class with the
  • wrong interface; make it fit
  • the interface a client
  • already expects
  • Facade:
  • MANY classes; invent a new,
  • simpler interface for them
  • both wrap; the goal differs

Other neighbours

Two more neighbours. A mediator also sits in the middle of many classes, but those classes know the mediator and send messages through it, so traffic flows both ways. With a facade, the subsystem has no idea the facade exists, and calls only flow downward. Decorator and Proxy keep the same interface as the object they wrap. A facade offers a different, simpler interface.

Facade vs the rest
  • Mediator:
  • peers talk THROUGH it and
  • know it; two-way traffic
  • Facade:
  • subsystem does not know it;
  • calls only flow downward
  • Decorator, Proxy:
  • keep the SAME interface
  • Facade:
  • offers a NEW, simpler one

Already in Java

You already use facades. SLF4J, the popular Java logging library, is literally named Simple Logging Facade for Java: your code calls one small logger API, and it forwards to whichever logging library sits underneath. Spring's JdbcTemplate hides opening connections, preparing statements, reading result sets and closing everything. And in most Spring Boot apps, a service class that calls several repositories and clients is a facade in all but name.

Facades you know
  • SLF4J: the name means
  • Simple Logging Facade for Java
  • one logger API, any backend
  • Spring JdbcTemplate: hides
  • connections, statements,
  • result sets and cleanup
  • your service classes: often
  • facades over repositories
  • and clients

In LLD interviews

In machine coding rounds, the facade is usually the top level service that the demo code calls. In a movie booking design, a booking service coordinates seat locks, payment and notifications. A vending machine exposes one front panel over the coin box, the stock and the dispenser. A library system offers check out and return. Name the pattern, keep the class thin, and show that each subsystem still has its own focused class.

Where it shows up
  • • movie booking: a booking
  • service over seat locks,
  • payment and notifications
  • • vending machine: one front
  • panel over coins, stock and
  • the dispenser
  • • library: checkOut, giveBack
  • • food delivery: placeOrder
  • mistake: logic in the facade

Say it like this

How to say it in an interview. OrderDesk is a thin facade over five subsystem classes. It runs reserve, charge, assign rider, enqueue and notify in that order, and undoes the earlier steps if a later one fails. Business rules stay in the classes that own the data, and staff tools can still call the subsystem directly. That answer shows you know both the benefit and the trap.

In the interview
  • "OrderDesk is a thin facade.
  • It runs reserve, charge,
  • assign rider, enqueue and
  • notify in order, and undoes
  • earlier steps on failure.
  • Business rules stay in the
  • subsystem classes, and staff
  • tools still call them
  • directly."

Interview questions

What is the Facade pattern?

A Facade is a class that offers a small, simple interface over a group of more complex classes. Callers use the facade instead of coordinating the subsystem themselves, so the call order, rules and undo steps live in one place.

What is the difference between Facade and Adapter?

An Adapter converts the interface of one existing class into an interface the client already expects, so it fits. A Facade usually wraps several classes and defines a new, simpler interface for them. Adapter is about compatibility; Facade is about simplicity.

How is a Facade different from a Mediator?

With a Mediator, the colleague classes know the mediator and talk to each other through it, so communication is two-way. With a Facade, the subsystem classes do not know the facade exists; calls flow one way, from the facade down into the subsystem.

Does a facade stop clients from using the subsystem directly?

No. A facade is a convenience for the common path, not an access barrier. Clients that need advanced features can still call the subsystem classes directly, and that is normal.

How do you stop a facade from becoming a god object?

Keep it thin: it should coordinate calls, not hold business rules. Put rules in the subsystem class that owns the data, and split large facades by use case, for example one for ordering and one for refunds.

How does a facade help testing?

Callers depend on one facade instead of five classes, so their tests can fake a single object. The facade itself receives its subsystem objects through the constructor, so its tests can pass in fakes such as a wallet that always declines.

Should a facade hold state, and can it be a singleton?

A facade is usually stateless apart from references to its subsystem objects, so one shared instance, such as a Spring singleton bean, is fine. Keep per-request data in parameters and return values, not fields, so concurrent calls do not interfere.

Give real examples of the Facade pattern in Java.

SLF4J is named Simple Logging Facade for Java: one logging API in front of whichever logging library is used. Spring JdbcTemplate hides connection, statement, result set and cleanup handling. Service classes that coordinate several repositories are also facades.