Facade
What you will learn on this page
Section titled “What you will learn on this page”- What the Facade pattern is for: giving a group of classes that must be used together one small interface for the jobs most callers need.
- How to write a facade in C++: a class that borrows the objects it coordinates and knows the order of the steps.
- Why a good facade does not hide the classes behind it, and how to decide what belongs in it and what does not.
- When a facade is just an extra class, and when it turns into a class that does too much.
The problem
Section titled “The problem”A house has a cinema room with five devices: lights, a projection screen that rolls down, a projector, an amplifier for the sound, and a film player. Two programs control the room: a remote-control app on a phone, and a voice assistant.
- FR-1 “Watch a film”: one action, from either program, sets up the whole room and starts the film.
- FR-2 “Finish”: one action returns every device to rest.
- FR-3 People can still adjust single devices during the film, such as the volume or the lights.
- FR-4 Asking for a film the player does not have must leave the room as it was, not half switched on.
- C-1 (constraint) The device classes are already used on their own, for example by the house’s lighting app, and must not change.
The devices
Section titled “The devices”Each device is a small class with its own rules:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The room's dimmable lights. The only state is a brightness from 0 (off)// to 100 (full), and a new Lights object starts at full brightness.// `final` means no class can inherit from this one: each device is a// plain, concrete class, and nothing here needs to replace it.class Lights final {public: void set_level(int percent); // 0 to 100; throws std::out_of_range otherwise int level() const { return level_; }
private: int level_ = 100;};
// The projection screen: rolled up (the starting state) or lowered. It// has no rules at all; lowering a screen that is already down is fine.class Screen final {public: void lower() { down_ = true; } void raise() { down_ = false; } bool is_down() const { return down_; }
private: bool down_ = false;};
// The projector: off or on, and showing one input (the tv or the// player). Its rule is about order: the input can only be chosen while it// is on, so set_input on a projector that is off throws std::logic_error.// Switching it off also puts the input back to tv, its starting value.class Projector final {public: void power_on() { on_ = true; } // switching on twice is harmless void power_off(); // also returns the input to tv void set_input(Source source); // only while on; throws std::logic_error when off bool is_on() const { return on_; } Source input() const { return input_; }
private: bool on_ = false; Source input_ = Source::tv;};
// The amplifier, which makes the sound. Like the projector, it must be on// before its input or volume is set (std::logic_error otherwise), and the// volume must be 0 to 100 (std::out_of_range otherwise). Its input starts// as tv, and power_off leaves the input and volume as they were. Nothing// here knows that the input must be the player for a film to have sound:// that rule involves two devices, so no single device can enforce it.class Amplifier final {public: void power_on() { on_ = true; } void power_off() { on_ = false; } void set_input(Source source); // only while on; throws std::logic_error when off void set_volume(int volume); // only while on; 0 to 100 bool is_on() const { return on_; } Source input() const { return input_; } int volume() const { return volume_; }
private: bool on_ = false; Source input_ = Source::tv; int volume_ = 20;};
// The film player. It is given its library of titles when it is made,// and can play only one of those, and only while it is on. playing()// returns the title now playing, or an empty string when nothing is.class Player final {public: // The library is taken by value and then moved into the member. A // named set from the caller is copied into the parameter; a brace list // of titles, as in main, builds the parameter directly. std::move then // hands the parameter's contents to library_ without a second copy. // `explicit` stops a bare std::set from silently turning into a Player. explicit Player(std::set<std::string> library) : library_{std::move(library)} {} void power_on() { on_ = true; } void power_off(); // also stops playing // A std::set holds each title at most once, so count is 1 when the // title is in the library and 0 when it is not. bool has(const std::string& title) const { return library_.count(title) != 0; } // Only while on (std::logic_error otherwise), and only a title it has // (std::invalid_argument otherwise). Playing while a film is already // playing simply switches to the new title. void play(const std::string& title); void stop() { playing_.clear(); } bool is_on() const { return on_; } const std::string& playing() const { return playing_; } // empty when stopped
private: std::set<std::string> library_; bool on_ = false; std::string playing_;};Some of the rules are about order and some about values. The
devices enforce them by throwing: std::logic_error for a command in
the wrong order, std::out_of_range for a value outside 0 to 100, and
std::invalid_argument for a title the player does not have (the last
two are kinds of std::logic_error):
| Device | Rule |
|---|---|
Projector |
the input can be chosen only while it is on |
Amplifier |
the input and volume can be set only while it is on; volume is 0 to 100 |
Player |
it can play only while it is on, and only a title in its library |
Lights |
the level is 0 to 100 percent |
And one rule is not enforced by any device, because no single device knows it: for sound, the amplifier’s input must be the player. Forget that step and the film plays in silence.
The straightforward solution
Section titled “The straightforward solution”Each program drives the devices itself. The remote-control app’s “watch” button was written first, carefully; the voice assistant’s was written later, by someone else, from memory:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The remote-control app's "watch" button, written first and carefully.// Every client takes all five devices by reference (`&`): it changes the// caller's real devices, not copies. The nine steps run in an order every// device accepts: each device is switched on before its input or volume// is set. Its one weakness is the title: play(title) is the last step, so// an unknown title throws std::invalid_argument after the other eight// steps have already changed the room.void remote_watch(const std::string& title, Lights& lights, Screen& screen, Projector& projector, Amplifier& amplifier, Player& player) { lights.set_level(10); screen.lower(); projector.power_on(); projector.set_input(Source::player); amplifier.power_on(); amplifier.set_input(Source::player); amplifier.set_volume(35); player.power_on(); player.play(title);}
// Written later, by someone else, from memory. It goes wrong in two// places, marked below. Neither shows up as a compile error, and the// second one does not even throw: the code runs and the room is wrong.void voice_watch(const std::string& title, Lights& lights, Screen& screen, Projector& projector, Amplifier& amplifier, Player& player) { player.power_on(); // Bug 1: the player is started before anything else, and the title is // only checked here. An unknown title throws, and the exception leaves // the function with the player already switched on. player.play(title); // an unknown title throws here, with the player already on lights.set_level(10); screen.lower(); projector.power_on(); projector.set_input(Source::player); amplifier.power_on(); // Bug 2: amplifier.set_input(Source::player) is missing. The amplifier // starts on its tv input and nothing changes it, so the film plays on // the projector while the amplifier listens to the tv. amplifier.set_volume(35); // the input is still tv: picture, but no sound}How this code works: voice_watch, step by step
Follow voice_watch twice, from a room at rest (lights 100%, screen up,
everything off, both inputs on tv).
With “Night Train”, a title the player has. Every call is accepted, so nothing throws:
player.power_on(), thenplayer.play("Night Train"): the film starts.- The lights go to 10% and the screen comes down.
- The projector is switched on and its input set to
player: the picture appears. - The amplifier is switched on and its volume set to 35. Its input is
never set, so it stays
tv, its starting value. The film plays with no sound, and no device complains, because no device knows the rule “for sound, the amplifier’s input must be the player”.
With “Unknown Film”. Step 1 switches the player on, then play
throws std::invalid_argument. The exception leaves the function at
once, so the other steps never run, but the player stays on. The
caller is left with a room that is neither at rest nor ready.
remote_watch has the steps in a working order, but it also calls
play last, so with an unknown title it would throw after changing the
other four devices and switching the player on. Both bugs come from the same place: each client
has to know, and get right, the whole procedure.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// A fresh room: every device in its starting state. The player is// given a library of two titles, written as a brace list that// becomes its std::set. Then the voice assistant's version runs,// and status() prints one line describing all five devices.Lights lights;Screen screen;Projector projector;Amplifier amplifier;Player player{{"Night Train", "The Long Field"}};before::voice_watch("Night Train", lights, screen, projector, amplifier, player);std::cout << "before: " << status(lights, screen, projector, amplifier, player) << "\n";The first line of the output below shows the result: the voice
assistant’s film is playing, the picture is on the screen, and the
amplifier is still on its tv input, so there is no sound.
The problems:
- Every client must know the whole procedure. Nine steps, in the right order, with the right values, repeated in each program. A third program (a wall panel, say) would repeat them again.
- Copies drift. The voice assistant’s version forgot
amplifier.set_input(Source::player). Nothing failed; it was simply wrong. - The order of checks matters, and is easy to get wrong. The voice version starts the player first, so an unknown title throws with the player already on (FR-4 fails).
- “Finish” does not exist. Each client would have to write its own, and each could leave a different device on.
- Every client depends on all five devices, so a change to any device, such as a new projector that needs a warm-up step, means changing every client.
The tests show the two bugs:
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_TEST(name) defines one test. LLD_CHECK(condition) records a failure// if the condition is false, and LLD_CHECK_THROWS(expression, type) fails// unless the expression throws that type of exception. They come from the// site's small test header, lld_test.hpp. Room is a helper struct in this// file holding a fresh set of the five devices (the player has the titles// "Night Train" and "The Long Field"), so every test starts from a room at rest.
// Runs the voice assistant's version with a title the player has, and// proves the amplifier is left on its tv input: the film has no sound.LLD_TEST(before_one_client_forgot_the_amplifier_input) { Room room; before::voice_watch("Night Train", room.lights, room.screen, room.projector, room.amplifier, room.player); LLD_CHECK(room.amplifier.input() == Source::tv); // no sound}
// Runs the voice version with a title the player does not have. It must// throw, and the check after it proves the player was switched on before// the throw: the room is left half started (FR-4 fails).LLD_TEST(before_an_unknown_title_leaves_the_room_half_started) { Room room; LLD_CHECK_THROWS(before::voice_watch("Unknown Film", room.lights, room.screen, room.projector, room.amplifier, room.player), std::invalid_argument); LLD_CHECK(room.player.is_on());}Step 1: sort the data and the functions
Section titled “Step 1: sort the data and the functions”Ask, for each job, how many devices it involves:
| Job | Devices involved | Where it goes |
|---|---|---|
| set a light level; lower or raise the screen | one | stays on Lights, Screen |
| switch the projector on; choose its input | one | stays on Projector |
| set the volume | one | stays on Amplifier (FR-3) |
| “watch a film”: the nine steps, in order | all five | one function in a new class: watch |
| check the title before changing anything | the player, before the other four | watch, as its first step (FR-4) |
| “finish”: every device back to rest | all five | one function in the same class: finish |
| the light level and volume to use for a film | data for watch |
a small Settings struct in the new class |
The jobs that involve one device stay on that device; nothing is gained by repeating them. The jobs that involve several devices, and the knowledge of their order, go in one new class. That class is the facade.
The pattern
Section titled “The pattern”Facade provides one simpler interface to a set of classes, a subsystem, for the jobs most callers need. The facade knows which classes to call, in which order, with which values. Callers who need only those jobs know only the facade; callers who need more still use the classes.
It has three participants:
- The facade: the class with the simple interface. Here,
HomeTheater. - The subsystem classes: the classes that do the work. Here, the five devices. They do not know the facade exists.
- The clients: the code that uses the facade. Here, the remote-control app and the voice assistant.
Text description of the diagram
A component diagram. The remote-control app and the voice assistant each call the HomeTheater facade, using watch and finish. The facade calls all five devices: Lights, Screen, Projector, Amplifier, and Player, which are grouped together and unchanged. The arrows are dashed because nothing here owns anything: every arrow is a call through a reference or pointer. Two arrows go around the facade: the remote-control app sets the volume on the Amplifier directly, and the house’s lighting app sets the level on the Lights directly. The devices have no arrows back to the facade or to the clients.
Diagram source (Mermaid)
flowchart LR
Remote([remote-control app]) -.->|watch, finish| HT[HomeTheater facade]
Voice([voice assistant]) -.->|watch, finish| HT
subgraph Devices [the devices, unchanged]
L[Lights]
S[Screen]
P[Projector]
A[Amplifier]
Pl[Player]
end
HT -.-> L
HT -.-> S
HT -.-> P
HT -.-> A
HT -.-> Pl
Remote -.->|volume| A
LightApp([lighting app]) -.->|level| LTwo things in the diagram matter more than the facade itself:
- The arrows only go one way. The devices do not know about the facade. They can still be used, tested, and changed on their own.
- Some arrows go around the facade. A facade is a convenience, not a wall. A client that needs finer control uses the device directly.
The C++ implementation
Section titled “The C++ implementation”The facade
Section titled “The facade”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The facade: the two things people usually want from the whole set of// devices, in the right order. It borrows the devices, which stay usable// directly for anything it does not cover.//// It owns nothing: it keeps one pointer to each device, and its job is to// know the procedure (which device, in which order, with which value).class HomeTheater final {public: // The two values a film needs, given once when the facade is made. // The `= 10` and `= 35` are default member values, so an empty `{}` // passed to the constructor means "light level 10, volume 35". struct Settings { int light_level = 10; int volume = 35; };
// The devices must outlive this object. Throws std::out_of_range // unless both settings are from 0 to 100. The devices are taken as // references, so a caller cannot pass a null device; the constructor // stores their addresses in the pointer members below. HomeTheater(Lights& lights, Screen& screen, Projector& projector, Amplifier& amplifier, Player& player, Settings settings);
// Throws std::invalid_argument, before changing anything, if the // player does not have the title. // Otherwise sets up all five devices in an order they accept and starts // the film. Calling it again while a film plays switches to the new title. void watch(const std::string& title); // Returns every device to rest: player, amplifier and projector off, // screen up, lights at 100%. Never throws, and is safe to call twice. void finish();
private: // Borrowed, not owned: pointers to devices that live elsewhere (in the // example, in main). The facade never deletes them. Pointers rather // than reference members keep the class copy-assignable. Lights* lights_; Screen* screen_; Projector* projector_; Amplifier* amplifier_; Player* player_; Settings settings_;};- It borrows the devices. The constructor takes references and stores pointers. The devices exist before the facade, are used by other code too (C-1, FR-3), and outlive it.
- Its interface is two functions, named after what people want, not
after the devices:
watchandfinish. - Settings are data, given once. The light level and volume for a
film are in a
Settingsstruct with sensible defaults, so the facade’s functions do not need them as parameters. - No interfaces, no virtual functions. Nothing here needs to replace the facade, so it is a plain concrete class. If a client must be tested without the facade, that is a different need (see When the requirements change).
The procedure
Section titled “The procedure”VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// The constructor's member initialiser list (after the `:`) stores the// address of each device (`&lights` is "the address of lights") and a copy// of the settings. Then the body checks the settings.HomeTheater::HomeTheater(Lights& lights, Screen& screen, Projector& projector, Amplifier& amplifier, Player& player, Settings settings) : lights_{&lights}, screen_{&screen}, projector_{&projector}, amplifier_{&lifier}, player_{&player}, settings_{settings} { // Checked here, so that watch cannot fail half way through. // `valid` is a small local function (a lambda). The empty [] means it // uses nothing from around it: it only looks at its argument. // Throwing from a constructor means no HomeTheater is created at all, // so a facade with bad settings can never exist. const auto valid = [](int percent) { return percent >= 0 && percent <= 100; }; if (!valid(settings.light_level) || !valid(settings.volume)) { throw std::out_of_range{"light level and volume must be from 0 to 100"}; }}
// "Check, then change". The only check the facade cannot do in advance is// the title, so it does that first; after it, every step below is one the// device accepts. `->` calls a member function through a pointer:// player_->has(title) means "ask the player this facade points to".void HomeTheater::watch(const std::string& title) { if (!player_->has(title)) { // check first: nothing is half switched on throw std::invalid_argument{"no such title: " + title}; } // Each device is switched on before its input or volume is set, because // the projector and amplifier throw std::logic_error otherwise. The // settings were checked in the constructor, so set_level and // set_volume cannot throw std::out_of_range here. lights_->set_level(settings_.light_level); screen_->lower(); projector_->power_on(); projector_->set_input(Source::player); amplifier_->power_on(); amplifier_->set_input(Source::player); // the step voice_watch forgot: sound from the player amplifier_->set_volume(settings_.volume); player_->power_on(); player_->play(title); // not refused now: the player is on and has the title}
// The reverse of watch, roughly: the player first, so the film stops// before its sound and picture go. Every call here is one the devices// accept in any state, so finish never throws and can be called before// any film, or twice. It always sets the lights to 100%, whatever they were.void HomeTheater::finish() { player_->power_off(); amplifier_->power_off(); projector_->power_off(); screen_->raise(); lights_->set_level(100);}How this code works: HomeTheater::watch and finish
watch has two halves: check, then change.
- Check.
player_->has(title)is the only question that can make the procedure fail, so it is asked before any device is touched. If the answer is no,watchthrows and the room is exactly as it was. - Change. The nine device calls run in an order every device
accepts. The settings were checked when the facade was made, so
set_levelandset_volumeget valid values.
Here is the room after each step of watch("Night Train") with the
default settings, starting from rest. A dash means “unchanged”.
| Step | Lights | Screen | Projector | Amplifier | Player |
|---|---|---|---|---|---|
| start | 100% | up | off, tv |
off, tv, volume 20 |
off |
has("Night Train") is true |
- | - | - | - | - |
lights_->set_level(10) |
10% | - | - | - | - |
screen_->lower() |
- | down | - | - | - |
projector_->power_on() |
- | - | on, tv |
- | - |
projector_->set_input(player) |
- | - | on, player |
- | - |
amplifier_->power_on() |
- | - | - | on, tv, volume 20 |
- |
amplifier_->set_input(player) |
- | - | - | on, player, 20 |
- |
amplifier_->set_volume(35) |
- | - | - | on, player, 35 |
- |
player_->power_on() |
- | - | - | - | on |
player_->play("Night Train") |
- | - | - | - | playing Night Train |
The room after the last row is the line the test watch_sets_up_every_device expects:
lights 10%, screen down, projector on player, amplifier on player volume 35, playing Night Train.
finish undoes it: the player off (which also stops the film), the
amplifier off, the projector off (which also puts its input back to
tv), the screen up, and the lights to 100%. None of these calls has a
rule that can be broken, so finish works in any state. One detail:
switching the amplifier off keeps its input and volume. The status line
shows only amplifier off for an amplifier that is off, so it still
matches the at-rest line, and the next watch sets both again anyway.
- The constructor checks the settings, so a bad volume is refused when the facade is made, not half way through a film.
watchchecks the title first. If the player does not have it,watchthrows before any device has changed (FR-4). After that check, the steps run in an order every device accepts, and the settings are already known to be valid, so no device rejects a command (only running out of memory could still interrupt it).- The order is written once. Projector on before its input; amplifier on before its input and volume; the amplifier’s input set to the player, the step the voice version forgot.
finishis safe to call at any time, even twice or before any film: each device’s off and raise functions do nothing harmful when the device is already at rest. (It does set the lights to 100%, whatever they were.)
class HomeTheater final
the facade: coordinates the devices it borrows
Data members
Lights* lights_;borrowed: must outlive the facadeScreen* screen_;Projector* projector_;Amplifier* amplifier_;Player* player_;Settings settings_;struct Settings { int light_level = 10; int volume = 35; }, checked in the constructor
Member functions
HomeTheater(Lights&, Screen&, Projector&, Amplifier&, Player&, Settings);throws std::out_of_range for bad settingsvoid watch(const std::string& title);throws std::invalid_argument, changing nothing, for an unknown titlevoid finish();
class Amplifier final
a subsystem class, unchanged; the others are similar small classes
Data members
bool on_;Source input_;int volume_;
Member functions
void power_on();void power_off();void set_input(Source source);only while onvoid set_volume(int volume);only while on; 0 to 100bool is_on() const;Source input() const;int volume() const;
namespace global
not a real namespace: free functions at file scope
Functions
std::string status(const Lights&, const Screen&, const Projector&, const Amplifier&, const Player&);for the example's output
The outline shows one device as an example; the other four are similar small classes, each with its own functions and rules.
Ownership and lifetime
Section titled “Ownership and lifetime”- Something outside the facade owns the devices. In the example it
is
main, which creates them as local variables before the facade. In a real house controller it would be the object that starts the program and connects to the hardware. - The facade borrows all five, through pointers set in its constructor. The rule is that every device must outlive the facade. Creating the devices first and the facade after them, in the same scope, keeps the rule, because local variables are destroyed in the reverse order.
- The constructor takes references, so a null device cannot be passed, and stores pointers, so the facade can still be copy-assigned. (A copy is a second facade for the same room, which is harmless here.)
- Why not own the devices? If the facade owned them, the lighting app and the volume control would have to go through it, or ask it for references, and the facade would grow a function for every device operation. Owning is right when no other code needs the subsystem objects, as with a library’s entry class that creates its own parts; the facade then also decides their lifetime, and callers can no longer go around it.
- Threads: the facade adds no locking. If the remote app and the voice assistant can run at the same time, two calls at once would be a data race on the devices (undefined behaviour), not just steps in a mixed-up order. A real controller would run all commands on one thread, or protect the devices with one lock that the facade and every direct caller use.
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// main owns the devices: they are local variables, created before the// facade. Local variables are destroyed in reverse order, so the// facade goes first and its pointers never outlive the devices.Lights lights;Screen screen;Projector projector;Amplifier amplifier;Player player{{"Night Train", "The Long Field"}};// The last argument, {}, is a default Settings: light level 10, volume 35.HomeTheater theater{lights, screen, projector, amplifier, player, {}};
theater.watch("Night Train");std::cout << "watch: " << status(lights, screen, projector, amplifier, player) << "\n";
amplifier.set_volume(50); // finer control: use the device directlystd::cout << "louder: " << status(lights, screen, projector, amplifier, player) << "\n";
theater.finish();std::cout << "finish: " << status(lights, screen, projector, amplifier, player) << "\n";
// The room is at rest again. watch checks the title before touching any// device, so it throws std::invalid_argument and the catch block prints// the message; the "after" line then shows that nothing changed.try { theater.watch("Unknown Film");} catch (const std::invalid_argument& error) { std::cout << "refused: " << error.what() << "\n";}std::cout << "after: " << status(lights, screen, projector, amplifier, player) << "\n";before: lights 10%, screen down, projector on player, amplifier on tv volume 35, playing Night Trainwatch: lights 10%, screen down, projector on player, amplifier on player volume 35, playing Night Trainlouder: lights 10%, screen down, projector on player, amplifier on player volume 50, playing Night Trainfinish: lights 100%, screen up, projector off, amplifier off, player offrefused: no such title: Unknown Filmafter: lights 100%, screen up, projector off, amplifier off, player offRead the output against the requirements:
before:is the voice assistant’s version: everything is on, but the amplifier’s input istv.watch:is the facade: the same devices, and the amplifier’s input isplayer(FR-1).louder:shows the volume changed through the amplifier directly, while the film plays (FR-3). The facade did not need aset_volumefunction.finish:shows every device at rest (FR-2).refused:andafter:: an unknown title is refused, and the room is exactly as it was (FR-4).
VerifiedCompiled and tested with GNU 11.4.0 and Clang 14.0.0 (C++20, 2026-12-01).
// LLD_CHECK_EQ(actual, expected) fails, and prints both values, unless they// are equal. room.status() is the same one-line description of the five// devices that the example prints, and at_rest is that line for a room// where nothing has been touched:// "lights 100%, screen up, projector off, amplifier off, player off".// Each test makes its own Room and its own HomeTheater, so no test sees// another test's changes.
// After watch, every device is in its film state, checked all at once by// comparing the whole status line. The two string literals next to each// other are joined by the compiler into one string.LLD_TEST(watch_sets_up_every_device) { Room room; HomeTheater theater{room.lights, room.screen, room.projector, room.amplifier, room.player, {}}; theater.watch("Night Train"); LLD_CHECK_EQ(room.status(), std::string{"lights 10%, screen down, projector on player, " "amplifier on player volume 35, playing Night Train"});}
// finish after a film gives exactly the at-rest line, and a second finish// on a room already at rest changes nothing and does not throw.LLD_TEST(finish_returns_every_device_to_rest) { Room room; HomeTheater theater{room.lights, room.screen, room.projector, room.amplifier, room.player, {}}; theater.watch("Night Train"); theater.finish(); LLD_CHECK_EQ(room.status(), at_rest); theater.finish(); // finishing twice is harmless LLD_CHECK_EQ(room.status(), at_rest);}
// FR-4: watch with a title the player lacks throws, and the whole room is// still at rest. Any device changed before the check would show up as a// difference in the status line.LLD_TEST(an_unknown_title_changes_nothing) { Room room; HomeTheater theater{room.lights, room.screen, room.projector, room.amplifier, room.player, {}}; LLD_CHECK_THROWS(theater.watch("Unknown Film"), std::invalid_argument); LLD_CHECK_EQ(room.status(), at_rest);}
// Settings{30, 60} sets light_level to 30 and volume to 60, in the order// the members are declared. watch must use these values, not the defaults.LLD_TEST(the_settings_choose_the_light_level_and_volume) { Room room; HomeTheater theater{room.lights, room.screen, room.projector, room.amplifier, room.player, HomeTheater::Settings{30, 60}}; theater.watch("The Long Field"); LLD_CHECK_EQ(room.lights.level(), 30); LLD_CHECK_EQ(room.amplifier.volume(), 60);}
// A volume of 150 is refused when the facade is made, not later in watch.// HomeTheater(...) here creates a temporary facade inside the check, only// to see whether its constructor throws.LLD_TEST(settings_out_of_range_are_refused_at_construction) { Room room; const HomeTheater::Settings too_loud{10, 150}; LLD_CHECK_THROWS(HomeTheater(room.lights, room.screen, room.projector, room.amplifier, room.player, too_loud), std::out_of_range);}
// FR-3: the facade does not hide the devices. While the film plays, the// test changes the volume and lights directly; the new volume sticks and// the film keeps playing.LLD_TEST(the_devices_stay_usable_directly) { Room room; HomeTheater theater{room.lights, room.screen, room.projector, room.amplifier, room.player, {}}; theater.watch("Night Train"); room.amplifier.set_volume(50); room.lights.set_level(0); LLD_CHECK_EQ(room.amplifier.volume(), 50); LLD_CHECK_EQ(room.player.playing(), std::string{"Night Train"});}
// A second watch while a film plays is not refused: switching the devices// on again is harmless, and play replaces the title.LLD_TEST(watching_again_switches_the_title) { Room room; HomeTheater theater{room.lights, room.screen, room.projector, room.amplifier, room.player, {}}; theater.watch("Night Train"); theater.watch("The Long Field"); LLD_CHECK_EQ(room.player.playing(), std::string{"The Long Field"});}
// The rules the facade relies on are enforced by the devices themselves,// with no facade involved. std::out_of_range is itself a kind of// std::logic_error; the volume check is written with the narrower type,// so it proves the amplifier objected to the value 101, not to being off.LLD_TEST(the_devices_reject_commands_in_the_wrong_order) { Amplifier amplifier; LLD_CHECK_THROWS(amplifier.set_volume(10), std::logic_error); amplifier.power_on(); LLD_CHECK_THROWS(amplifier.set_volume(101), std::out_of_range); Projector projector; LLD_CHECK_THROWS(projector.set_input(Source::player), std::logic_error);}- The tests use the real devices. They are plain in-memory classes, so there is nothing to fake, and testing the facade with them checks the thing that matters: that the devices accept the facade’s order.
an_unknown_title_changes_nothingcompares the whole room’s status with the status at rest, so a step taken too early would fail it.finish_returns_every_device_to_restalso callsfinishtwice.the_devices_stay_usable_directlyandthe_devices_reject_commands_in_the_wrong_ordercheck the two things the facade relies on: the devices still work alone, and they enforce their own rules.
Limits of the example
Section titled “Limits of the example”Real devices fail in ways these classes cannot: a projector lamp that
does not start, or an amplifier that does not answer. Then watch
could fail after some devices have changed. A real facade would have to
choose what to do, such as calling finish to return the room to rest
before reporting the failure. That choice belongs in the facade,
because only the facade knows the whole procedure.
Deciding what goes in a facade
Section titled “Deciding what goes in a facade”The hardest part of a facade is its scope: which functions it has. Use these questions for each candidate:
- Does it involve more than one subsystem class, or a fixed order of steps? Then it is a candidate for the facade. “Watch” and “finish” do.
- Is it one call to one class? Then leave it on that class.
“Set the volume” is one call; a
HomeTheater::set_volumethat only callsamplifier_->set_volumeadds a function and saves nothing. - Is it a job most clients need? A facade is for the common case. A rare job that involves several devices, such as a calibration routine used once a year, may belong in its own function or class.
- Would putting it in the facade stop someone doing something they need? Then do not put it there instead of the classes: offer it as well as them.
A facade with many functions that are one call to one class is becoming a pass-through, and one that collects every job in the system is becoming a god class. Both are covered under Common misuse.
When to use it
Section titled “When to use it”- Several classes must be used together, in an order, and many callers need the same few jobs from them.
- A library or subsystem is complicated, and most of your code needs only a small part of it. A facade gives that part a name and a small interface.
- Callers should not depend on the subsystem’s details. If the projector is replaced by one that needs a warm-up step, only the facade changes.
- Between layers of a program, as the one entry point the layer above uses. A page on layered architecture is planned.
When not to use it
Section titled “When not to use it”- There is only one caller. A function in that caller, with a good name, does the same job.
- The subsystem is already simple. One class with a clear interface needs no facade.
- The interfaces do not fit. If the problem is that one class has the wrong interface for its callers, that is Adapter. A facade simplifies; it does not translate one interface into another.
- You need the classes to coordinate with each other, both ways, as they change. A facade is called by clients; the devices never call it. Two-way coordination between peers is Mediator.
- One more class for readers to find, and one more place where the order of steps lives. This is the point, but it is still a class.
- Callers can still go around it. The facade cannot stop a client
setting the amplifier’s input back to
tv. It makes the right thing easy, not the wrong thing impossible. - It tends to grow. Every new request (“can it also…?”) lands in the facade, because it is the obvious place. Keep applying the scope questions above.
Common misuse
Section titled “Common misuse”- A pass-through facade.
set_volume,set_light_level,lower_screen, and so on, each forwarding one call. The facade now has the whole subsystem’s interface, and is no simpler. - A god facade. Every job in the house in one class: films, music, heating, alarms. Split it by job: a cinema-room facade, a heating facade.
- Hiding what callers need. Making the devices private to the facade, so that the volume can only be set through it, forces either a pass-through function for every operation or callers who cannot do their job.
- A singleton facade. A facade is often the one obvious object, so
it is tempting to make it a global. Create it in
mainand pass it to the clients instead; see Singleton. - Business rules hidden in it that callers going around it do not
get. If “the volume must never exceed 80” is a rule, it belongs in
the amplifier, or in whatever every caller uses, not only in
watch.
When the requirements change
Section titled “When the requirements change”- “The new projector needs 20 seconds to warm up before its input
can be set.” Only
watchchanges (and the projector class). The clients do not. - “Add a music mode: the player on, the amplifier on, the projector
off, and the lights at 60%.” Several devices, in an order, used by
several clients: add
listen(const std::string& album)to the facade. - “Test the voice assistant without the real facade.” Then the
voice assistant needs an interface it depends on, such as
CinemaRoomwithwatchandfinish, whichHomeTheaterimplements. That is ordinary dependency inversion, added when a test needs it, not before. - “A second cinema room.” Create a second set of devices and a
second
HomeTheaterfor them. Because the facade borrows its devices and is not a global, nothing else changes.
Exercise
Section titled “Exercise”Exercise: Decide the facade's scope
The household asks for five more features. For each one, decide: does
it go in HomeTheater, on a device, or somewhere else? Give the reason.
- Pause and resume the film (suppose
Playergainspause()andresume()). - A “night mode” that keeps the volume at 25 or below, however it is set, after 10 p.m.
- A query that says whether the room is in use, for the house’s heating to use.
- “Intermission”: pause the film and raise the lights to 50%, then undo both when the film continues.
- “Set the volume to 40.”
Show the explained answer
1. On the player. One call to one device. A
HomeTheater::pause that only calls player_->pause() would be a
pass-through. Clients call player.pause() directly.
2. Not in the facade. “However it is set” includes clients that go
around the facade, so the facade cannot enforce it. A rule that must
always hold belongs with the thing it protects: in the amplifier (if
you can change it, which C-1 does not allow here), or in a class that
owns the amplifier and is the only way to reach it. That class
would not be a facade any more; it would be a wrapper that every
caller must use. The facade can still choose a lower volume in its
Settings at night, but that only affects watch.
3. In the facade, as a const member function, such as
bool in_use() const. It reads several devices (is the player playing,
is the projector on?) and its meaning, “in use as a cinema”, is the
facade’s idea, not any single device’s.
4. In the facade. It involves two devices, in an order, and its
“undo” must remember the light level before the intermission. That
remembered level is new state for HomeTheater, which is fine: it is
state about the procedure, and only the facade has it.
5. On the amplifier. One call to one device, as in the example’s “louder” line.
The pattern in the answers: several classes, or a procedure, go in the facade; one call stays on its class; a rule that must always hold cannot live in a facade, because a facade can be gone around.
Related patterns
Section titled “Related patterns”- Adapter changes one class’s interface into the one callers expect; Facade gives several classes one simpler interface. A facade can use adapters inside it, to talk to classes with awkward interfaces. See Adapter.
- Mediator also sits among several classes, but they know it and call it, and it coordinates them in both directions. A facade’s classes do not know it exists. See Mediator.
- Singleton is often combined with Facade, and usually should not be; see Singleton.
- Layered architecture uses facades as the entry point to each layer. A page is planned.
Summary
Section titled “Summary”- A facade gives a subsystem one small interface for the jobs most callers need, and holds the knowledge of which classes to call, in which order.
- Put in it what involves several classes or a fixed procedure. Leave single calls on their classes.
- Do not hide the subsystem: callers who need finer control use the classes directly. A facade is a convenience, not a wall, so it cannot enforce rules on its own.
- When other code also uses the subsystem objects, a facade borrows them, and the objects must outlive it. Check what can fail before changing anything, so a refused request leaves no half-finished state.
- A facade with a function for every subsystem operation, or with every job in the program, has lost its purpose.