Facade Pattern
StructuralWhat is it?
Provides a simple interface to a complex subsystem, making it easier to use.
Why use it?
The Facade pattern provides a simplified interface to a complex subsystem, making it easier to use. It hides the complexities of the subsystem and provides a single point of entry, which is useful in reducing dependencies and improving the readability of the code.
Code Example
typescript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// Facade Pattern Example
// Complex subsystem classes
class CPU {
freeze() {
console.log('CPU: Freezing processor');
}
jump(position) {
console.log(`CPU: Jumping to position ${position}`);
}
execute() {
console.log('CPU: Executing instructions');
}
}
class Memory {
load(position, data) {
console.log(`Memory: Loading data "${data}" at position ${position}`);
}
}
class HardDrive {
read(lba, size) {
console.log(`HardDrive: Reading ${size} bytes from LBA ${lba}`);
return 'boot data';
}
}
class GPU {
initialize() {
console.log('GPU: Initializing graphics processor');
}
renderBootScreen() {
console.log('GPU: Rendering boot screen');
}
}
class PowerSupply {
turnOn() {
console.log('PowerSupply: Providing power to components');
}
turnOff() {
console.log('PowerSupply: Cutting power to components');
}
}
// Facade class
class ComputerFacade {
constructor() {
this.cpu = new CPU();
this.memory = new Memory();
this.hardDrive = new HardDrive();
this.gpu = new GPU();
this.powerSupply = new PowerSupply();
}
start() {
console.log('=== Starting Computer ===');
this.powerSupply.turnOn();
this.gpu.initialize();
this.gpu.renderBootScreen();
this.cpu.freeze();
this.memory.load(0x00, this.hardDrive.read(0x00, 1024));
this.cpu.jump(0x00);
this.cpu.execute();
console.log('=== Computer Started Successfully ===\n');
}
shutdown() {
console.log('=== Shutting Down Computer ===');
this.cpu.freeze();
this.powerSupply.turnOff();
console.log('=== Computer Shut Down ===\n');
}
}
// Usage - Simple interface hiding complexity
const computer = new ComputerFacade();
computer.start();
computer.shutdown();
// Another example: Home Theater Facade
class Amplifier {
on() { console.log('Amplifier: Turning on'); }
off() { console.log('Amplifier: Turning off'); }
setVolume(level) { console.log(`Amplifier: Setting volume to ${level}`); }
setSurroundSound() { console.log('Amplifier: Surround sound enabled'); }
}
class DVDPlayer {
on() { console.log('DVD Player: Turning on'); }
off() { console.log('DVD Player: Turning off'); }
play(movie) { console.log(`DVD Player: Playing "${movie}"`); }
stop() { console.log('DVD Player: Stopped'); }
}
class Projector {
on() { console.log('Projector: Turning on'); }
off() { console.log('Projector: Turning off'); }
wideScreenMode() { console.log('Projector: Wide screen mode enabled'); }
}
class TheaterLights {
dim(level) { console.log(`Lights: Dimming to ${level}%`); }
on() { console.log('Lights: Turning on'); }
}
class PopcornMaker {
on() { console.log('Popcorn Maker: Turning on'); }
off() { console.log('Popcorn Maker: Turning off'); }
pop() { console.log('Popcorn Maker: Popping corn!'); }
}
// Home Theater Facade
class HomeTheaterFacade {
constructor() {
this.amp = new Amplifier();
this.dvd = new DVDPlayer();
this.projector = new Projector();
this.lights = new TheaterLights();
this.popcorn = new PopcornMaker();
}
watchMovie(movie) {
console.log('=== Get ready to watch a movie! ===');
this.popcorn.on();
this.popcorn.pop();
this.lights.dim(10);
this.projector.on();
this.projector.wideScreenMode();
this.amp.on();
this.amp.setSurroundSound();
this.amp.setVolume(8);
this.dvd.on();
this.dvd.play(movie);
console.log('=== Enjoy your movie! ===\n');
}
endMovie() {
console.log('=== Shutting down theater... ===');
this.dvd.stop();
this.dvd.off();
this.amp.off();
this.projector.off();
this.lights.on();
this.popcorn.off();
console.log('=== Theater shut down ===\n');
}
}
// Usage
const homeTheater = new HomeTheaterFacade();
homeTheater.watchMovie('The Matrix');
homeTheater.endMovie();
// API Facade example
class APIFacade {
constructor() {
this.baseURL = 'https://api.example.com';
}
async getUser(userId) {
try {
// Hide complex authentication, headers, error handling
const token = await this._authenticate();
const response = await fetch(`${this.baseURL}/users/${userId}`, {
headers: {
'Authorization': `Bearer ${token}`,
'Content-Type': 'application/json'
}
});
if (!response.ok) {
throw new Error('Failed to fetch user');
}
return await response.json();
} catch (error) {
console.error('Error fetching user:', error);
throw error;
}
}
async _authenticate() {
// Complex authentication logic hidden
return 'mock-token';
}
}
// Simple usage hiding all complexity
const api = new APIFacade();
// api.getUser(123).then(user => console.log(user));
Quick Facts
- Category
- Structural
- Common Use Cases
- Object composition, interface adaptation