Facade pattern
easy 50 minThe Facade pattern gives a group of classes one simple front.
Video lesson · Chapter 1 of 6
Make a prediction
Facade
1:03Reel
More reels
One idea each, a minute or less.
Adapter vs facade
0:34Reel
Theory
Read or listen first. About 2 min.
What it is
The Facade pattern is a structural design pattern. A facade is a class that offers a simple interface to a subsystem, a group of classes that work together.
The facade holds the parts and passes requests to them, usually several calls for one request. The parts do not know it.
It does not forbid direct use. It makes the usual case easy and leaves the unusual case possible.
Why it exists
Many small classes are good for those who build a system, and hard for those who use it. Without a front, each client learns all parts, their order and their numbers.
With a front, the knowledge exists once. Clients depend on one class, parts can be replaced, and tests of clients need one fake.
It is also a place for what concerns the whole operation: undo after a failure, time limits, one log line, protection against repeats.
A short history
1987
Ian Holland proposes the law of Demeter in the Demeter project at Northeastern University: talk only to your close friends. Facades are one way to follow it.
1994
The book Design Patterns appears on 31 October and lists Facade among its structural patterns.
2003
Eric Evans publishes Domain-Driven Design, which among other things describes layers that keep foreign models out. The Azure guide to this pattern speaks of a facade or adapter layer.
2023
Go 1.21 adds log/slog to its standard library: package functions such as slog.Info are a short front over a Logger and its Handler.
Words to know
- Facade
- The class with the simple interface.
- Subsystem
- The group of classes behind it.
- Wish
- Something a client wants as a whole, such as watch a movie.
- Coarse-grained
- Few large operations. The opposite is fine-grained.
- Remote facade
- A coarse front over a network.
- Service layer
- The operations of an application with rules and transactions.
- Compensation
- An action that makes up for an earlier one, such as a refund.
- Outbox
- Messages written down with the data, sent later.
- God object
- A class that knows and does too much.
- Seam
- A place where you can change what is behind without changing what is in front.
- Backend for frontend
- One remote facade for each kind of client.
The solution, twice
Reach the regular design first. Then go where a FAANG interviewer digs.
How it works
Step through the idea, or press Play.
Client asks for a wish. One call to one class
Understand it
Start here
One lever for a whole mill
A watermill has a gate, a wheel, a brake, a hopper and a chute. To make flour you must use all of them, in the right order. The Facade pattern gives you one lever. Behind it, everything is still there.
Visitors use the lever. Experts use the side door. The mill is the same mill.
Three parts
Facade
A few methods for common wishes:
watch_movie,place_order. Holds the parts, knows the order, passes the work on.Subsystem
The classes that do the work:
Tv,Lights,Inventory. They know nothing of the facade and can be used without it.Client
Calls the facade for the usual case. May go around it for the unusual one.
Why
What goes wrong without it
Movie night at home: lights down, television on, channel 3, projector on, speakers on, volume 50, DVD player on, play. Eight calls to five devices. Now three buttons in the house do this: the wall panel, the phone, and the voice assistant.
class Speakers: def __init__(self): self.on = False def turn_on(self): self.on = True def set_volume(self, percent): if not self.on: raise RuntimeError("the speakers are off") print("volume", percent)class Lights: def dim(self, percent): print("lights", percent)def wall_panel(lights, speakers): lights.dim(10) speakers.turn_on() speakers.set_volume(50)def phone(lights, speakers): # copied, then changed speakers.set_volume(50) speakers.turn_on() lights.dim(10)wall_panel(Lights(), Speakers())try: phone(Lights(), Speakers())except RuntimeError as error: print("phone:", error)The design that hurts
1/2One client
It must know three classes here, five in the real room, their order and their valid numbers.
uses
With a facade
- Clients know one class
- The order is written once
- Client tests need one fake
- A new projector ends at the facade
Without a facade
- Each client knows every part
- The order of calls is copied
- Every test needs five fakes
- A new projector means editing all clients
The idea
A front door
Write down what clients really want, in their words: watch a movie, end the movie. Make a class with exactly these methods. Give it the parts. Move the sequence of calls into it.
The Facade pattern in general
1/3The parts
They exist already and work. They may know each other, and none of them knows a facade.
useshas (lives on)
One call, eight calls
What a facade knows, so that clients need not
| Knowledge | Example | If a client forgets it |
|---|---|---|
| Which parts | The projector is needed too | Sound without a picture |
| Order | Turn on before volume | Error |
| Numbers | Channel 3 is the DVD input | The evening news |
| Stopping | Reverse order, all of them | The projector runs all night |
| Failure | No disc: lights on again | People sit in the dark |
| Threads | One start at a time | Two buttons, mixed steps |
Two pictures
The universal remote and the concierge
A universal remote has a button Movie night. It replaces none of the devices and none of their own remotes. It only presses their buttons for you, in order. A hotel concierge does the same with people: you ask once, and they call the taxi, the restaurant and the theatre. You could call them yourself, and sometimes you will.
Forms
Kinds of facade
Convenience facade
Short ways for common wishes over a library.
subprocess.runoverPopen.Module facade
The only public class of a package. Everything else is private to it.
Remote facade
Coarse methods over a network, so that one wish is one request.
Vendor facade
A small interface in front of a large third-party library. Often an adapter as well.
Facade over old code
New callers use the new front. Behind it the old parts are replaced one by one.
Two facades over one subsystem
1/2For guests
Two methods. No word about lamp hours.
useshas (lives on)
Choosing
When to use it and when not
Use it when
- A common wish needs several classes in a certain order
- Clients should not depend on the parts
- Layers of a system need an entry point
- A third-party library is larger than your need
- Several callers repeat the same calls
Leave it when
- The subsystem is already simple: one class, two methods
- Every client needs every option
- It would only pass calls on, one to one
- It would collect everything: a god object
- There is one caller, and a private method is enough
Do I need a facade?
Guests now want to choose the volume and the brightness. The facade has watch_movie(movie). What do you change?
BreaksEleven parameters
- How
watch_movie(movie, volume, light, channel, delay, ...)- Limit
- The facade has become as complicated as the parts.
- Choose when
- Never.
WorksGetters for the parts
- How
theater.speakers().set_volume(65)- Limit
- Clients depend on the parts again, through the facade. Law of Demeter.
- Choose when
- For an expert tool that says so.
StrongA small settings value with good defaults
- How
watch_movie(movie, Scene(volume=65)), and named scenes such asScene.LATE.- Limit
- The value grows slowly. Review it.
- Choose when
- When a few choices matter to most clients. Experts use the parts directly.
Neighbours
Facade and the patterns beside it
| Pattern | Purpose | Wraps | Do the parts know it? |
|---|---|---|---|
| Facade | Make many things easy | A group | No |
| Adapter | Make one thing fit an expected interface | One, mostly | No |
| Mediator | Let parts talk without knowing each other | A group | Yes, they call it |
| Proxy | Control access, same interface | One | No |
| Abstract factory | Hide which classes are created | Creation only | No |
| Service layer | The operations of an application, with transactions and rules | The domain | No |
| API gateway | One network entry for many services | Services | No |
What you gain and what you pay
Simple
One call for one wish, named in the client's words.
Loosely coupled
Parts can be replaced, and clients do not notice.
One home
Order, numbers, undo, metrics and logs of the operation stand in one place.
Magnet
Everybody adds one more method. Without care it becomes the class that knows everything.
Hidden cost
One harmless call may start eight others and a network request. Say so in the name or the documentation.
Summary
The whole topic in one minute.
Collect the wishes of one kind of client. One method per wish, the parts come from outside, the order and the numbers live inside. No arrow goes back.
Starting is all or nothing, stopping is as much as possible. Every step with an effect brings its undo.
In production: keys against repeats, an outbox for mails, one request per wish over a network, a guarded border, and a split by client before it becomes a god object.
- A facade is a simple front for a group of classes. The group stays usable without it.
- Methods are wishes of a client, not operations of the parts.
- It owns order, numbers, stopping and undo of the common operations.
- Parts do not know the facade. If they call it, it is a mediator.
- One facade for each kind of client. Split it when it grows.
- Across a network: one wish, one request, with a time limit and a key.