Mediator Pattern
BehavioralWhat is it?
Defines an object that encapsulates how a set of objects interact, promoting loose coupling by keeping objects from referring to each other explicitly.
Why use it?
The Mediator pattern defines an object that centralizes complex communications and control logic between objects in a system. Rather than having objects refer to each other directly, they communicate through the mediator. This promotes loose coupling and makes it easier to modify interactions without touching each component. It's often used in chat applications, UI form elements coordination, and event-based systems.
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Mediator Pattern Example
// Chat Room Mediator
class ChatRoom {
constructor() {
this.users = {};
this.messageHistory = [];
}
register(user) {
this.users[user.name] = user;
user.setChatRoom(this);
this.broadcast('system', `${user.name} has joined the chat`, user);
}
send(message, from, to = null) {
const timestamp = new Date().toLocaleTimeString();
const messageData = {
from: from.name,
to: to ? to.name : 'all',
message,
timestamp
};
this.messageHistory.push(messageData);
if (to) {
// Private message
to.receive(`[Private from ${from.name}] ${message}`, timestamp);
from.receive(`[Private to ${to.name}] ${message}`, timestamp);
} else {
// Broadcast to all users except sender
for (let key in this.users) {
if (this.users[key] !== from) {
this.users[key].receive(`[${from.name}] ${message}`, timestamp);
}
}
}
}
broadcast(type, message, excludeUser = null) {
const timestamp = new Date().toLocaleTimeString();
for (let key in this.users) {
if (this.users[key] !== excludeUser) {
this.users[key].receive(`[System] ${message}`, timestamp);
}
}
}
}
// User class
class User {
constructor(name) {
this.name = name;
this.chatRoom = null;
}
setChatRoom(chatRoom) {
this.chatRoom = chatRoom;
}
send(message, to = null) {
if (this.chatRoom) {
if (to) {
this.chatRoom.send(message, this, to);
} else {
this.chatRoom.send(message, this);
}
}
}
receive(message, timestamp) {
console.log(`${this.name} received at ${timestamp}: ${message}`);
}
}
// Usage
console.log('=== Chat Room Example ===');
const chatRoom = new ChatRoom();
const alice = new User('Alice');
const bob = new User('Bob');
const charlie = new User('Charlie');
chatRoom.register(alice);
chatRoom.register(bob);
chatRoom.register(charlie);
alice.send('Hello everyone!');
bob.send('Hey Alice!');
charlie.send('Hi there!', alice); // Private message to Alice
// Air Traffic Control Mediator
class AirTrafficControl {
constructor() {
this.aircraft = [];
this.runwayAvailable = true;
}
registerAircraft(aircraft) {
this.aircraft.push(aircraft);
aircraft.setATCMediator(this);
}
requestLanding(aircraft) {
if (this.runwayAvailable) {
this.runwayAvailable = false;
console.log(`ATC: ${aircraft.name} cleared for landing on runway.`);
// Notify other aircraft
this.aircraft.forEach(plane => {
if (plane !== aircraft) {
plane.notify(`${aircraft.name} is landing. Please maintain altitude.`);
}
});
// Simulate landing time
setTimeout(() => {
this.runwayAvailable = true;
console.log(`ATC: Runway is now clear.`);
this.notifyRunwayStatus();
}, 3000);
return true;
} else {
console.log(`ATC: ${aircraft.name} please circle. Runway occupied.`);
return false;
}
}
requestTakeoff(aircraft) {
if (this.runwayAvailable) {
this.runwayAvailable = false;
console.log(`ATC: ${aircraft.name} cleared for takeoff.`);
// Notify other aircraft
this.aircraft.forEach(plane => {
if (plane !== aircraft) {
plane.notify(`${aircraft.name} is taking off. Maintain safe distance.`);
}
});
setTimeout(() => {
this.runwayAvailable = true;
console.log(`ATC: Runway is now clear.`);
this.notifyRunwayStatus();
}, 2000);
return true;
} else {
console.log(`ATC: ${aircraft.name} hold position. Runway occupied.`);
return false;
}
}
notifyRunwayStatus() {
this.aircraft.forEach(plane => {
plane.notify('Runway is now available.');
});
}
broadcastWeatherUpdate(weather) {
console.log(`ATC: Weather update - ${weather}`);
this.aircraft.forEach(plane => {
plane.notify(`Weather update: ${weather}`);
});
}
}
class Aircraft {
constructor(name) {
this.name = name;
this.atc = null;
}
setATCMediator(atc) {
this.atc = atc;
}
requestLanding() {
console.log(`${this.name}: Requesting landing permission.`);
return this.atc.requestLanding(this);
}
requestTakeoff() {
console.log(`${this.name}: Requesting takeoff permission.`);
return this.atc.requestTakeoff(this);
}
notify(message) {
console.log(`${this.name} received: ${message}`);
}
}
// Usage
console.log('\n=== Air Traffic Control Example ===');
const atc = new AirTrafficControl();
const flight1 = new Aircraft('United 123');
const flight2 = new Aircraft('Delta 456');
const flight3 = new Aircraft('American 789');
atc.registerAircraft(flight1);
atc.registerAircraft(flight2);
atc.registerAircraft(flight3);
flight1.requestLanding();
flight2.requestLanding(); // Will be denied
atc.broadcastWeatherUpdate('Clear skies, wind 10 knots');
// UI Components Mediator
class FormMediator {
constructor() {
this.components = {};
}
register(name, component) {
this.components[name] = component;
component.setMediator(this);
}
notify(sender, event, data) {
switch(event) {
case 'country-changed':
this.handleCountryChange(data);
break;
case 'shipping-changed':
this.handleShippingChange(data);
break;
case 'calculate-total':
this.calculateTotal();
break;
}
}
handleCountryChange(country) {
console.log(`Mediator: Country changed to ${country}`);
// Update shipping options based on country
if (country === 'USA') {
this.components.shippingSelect.setOptions(['Standard', 'Express', 'Overnight']);
} else {
this.components.shippingSelect.setOptions(['International Standard', 'International Express']);
}
// Update tax rate
const taxRate = country === 'USA' ? 0.08 : 0.15;
this.components.taxField.setValue(taxRate);
this.calculateTotal();
}
handleShippingChange(option) {
console.log(`Mediator: Shipping changed to ${option}`);
const shippingCosts = {
'Standard': 5,
'Express': 15,
'Overnight': 30,
'International Standard': 20,
'International Express': 40
};
this.components.shippingCost.setValue(shippingCosts[option] || 0);
this.calculateTotal();
}
calculateTotal() {
const subtotal = this.components.subtotalField.getValue();
const tax = subtotal * this.components.taxField.getValue();
const shipping = this.components.shippingCost.getValue();
const total = subtotal + tax + shipping;
this.components.totalField.setValue(total);
console.log(`Mediator: Total calculated: $${total.toFixed(2)}`);
}
}
class FormComponent {
constructor(name, value = null) {
this.name = name;
this.value = value;
this.mediator = null;
}
setMediator(mediator) {
this.mediator = mediator;
}
setValue(value) {
this.value = value;
console.log(`${this.name}: Value set to ${value}`);
}
getValue() {
return this.value;
}
}
class SelectComponent extends FormComponent {
constructor(name, options = []) {
super(name);
this.options = options;
}
setOptions(options) {
this.options = options;
console.log(`${this.name}: Options updated to [${options.join(', ')}]`);
}
select(option) {
if (this.options.includes(option)) {
this.value = option;
console.log(`${this.name}: Selected "${option}"`);
this.mediator.notify(this, this.name === 'countrySelect' ? 'country-changed' : 'shipping-changed', option);
}
}
}
// Usage
console.log('\n=== Form Mediator Example ===');
const formMediator = new FormMediator();
// Create components
const countrySelect = new SelectComponent('countrySelect', ['USA', 'Canada', 'Mexico']);
const shippingSelect = new SelectComponent('shippingSelect', []);
const subtotalField = new FormComponent('subtotalField', 100);
const taxField = new FormComponent('taxField', 0);
const shippingCost = new FormComponent('shippingCost', 0);
const totalField = new FormComponent('totalField', 0);
// Register components
formMediator.register('countrySelect', countrySelect);
formMediator.register('shippingSelect', shippingSelect);
formMediator.register('subtotalField', subtotalField);
formMediator.register('taxField', taxField);
formMediator.register('shippingCost', shippingCost);
formMediator.register('totalField', totalField);
// Simulate user interactions
countrySelect.select('USA');
shippingSelect.select('Express');
console.log('\n--- Changing country to Canada ---');
countrySelect.select('Canada');
shippingSelect.select('International Express');
Quick Facts
- Category
- Behavioral
- Common Use Cases
- Communication patterns, algorithms