Observer Pattern
BehavioralWhat is it?
Defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically. This is commonly used in event handling in JavaScript.
Why use it?
The Observer pattern defines a one-to-many dependency between objects, so when one object changes state, all its dependents are notified and updated automatically. This is useful for implementing event handling systems or when an object needs to notify other objects without being tightly coupled to them.
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
// Observer Pattern Example
// Subject(Observable)
class Subject {
constructor() {
this.observers = [];
}
subscribe(observer) {
this.observers.push(observer);
console.log(`Observer ${observer.name} subscribed`);
}
unsubscribe(observer) {
const index = this.observers.indexOf(observer);
if (index > -1) {
this.observers.splice(index, 1);
console.log(`Observer ${observer.name} unsubscribed`);
}
}
notify(data) {
console.log(`Notifying ${this.observers.length} observers...`);
this.observers.forEach(observer => observer.update(data));
}
}
// Concrete Subject - News Agency
class NewsAgency extends Subject {
constructor() {
super();
this.news = [];
}
addNews(headline) {
this.news.push({
headline,
timestamp: new Date(),
id: this.news.length + 1
});
this.notify(this.news[this.news.length - 1]);
}
getLatestNews() {
return this.news[this.news.length - 1];
}
}
// Observer interface
class Observer {
constructor(name) {
this.name = name;
}
update(data) {
throw new Error('Update method must be implemented');
}
}
// Concrete Observers
class NewsChannel extends Observer {
update(news) {
console.log(`${this.name} broadcasting: "${news.headline}" at ${news.timestamp.toLocaleTimeString()}`);
}
}
class NewsWebsite extends Observer {
update(news) {
console.log(`${this.name} posting article: "${news.headline}" (ID: ${news.id})`);
}
}
class MobileApp extends Observer {
update(news) {
console.log(`${this.name} push notification: "${news.headline}"`);
}
}
// Usage
const newsAgency = new NewsAgency();
const cnn = new NewsChannel('CNN');
const bbcWebsite = new NewsWebsite('BBC Website');
const newsApp = new MobileApp('News App');
// Subscribe observers
newsAgency.subscribe(cnn);
newsAgency.subscribe(bbcWebsite);
newsAgency.subscribe(newsApp);
// Publish news
console.log('\n--- Publishing news ---');
newsAgency.addNews('Breaking: Major scientific discovery announced!');
console.log('\n--- Publishing another news ---');
newsAgency.addNews('Sports: Local team wins championship!');
// Unsubscribe one observer
console.log('\n--- CNN unsubscribing ---');
newsAgency.unsubscribe(cnn);
console.log('\n--- Publishing news after CNN unsubscribed ---');
newsAgency.addNews('Weather: Storm approaching the east coast');
// Event Emitter Implementation(Node.js style)
class EventEmitter {
constructor() {
this.events = {};
}
on(event, listener) {
if (!this.events[event]) {
this.events[event] = [];
}
this.events[event].push(listener);
}
off(event, listenerToRemove) {
if (!this.events[event]) return;
this.events[event] = this.events[event].filter(
listener => listener !== listenerToRemove
);
}
emit(event, data) {
if (!this.events[event]) return;
this.events[event].forEach(listener => listener(data));
}
}
// Stock Price Example
class StockPrice extends EventEmitter {
constructor(symbol, price) {
super();
this.symbol = symbol;
this.price = price;
}
setPrice(price) {
const oldPrice = this.price;
this.price = price;
this.emit('price-changed', {
symbol: this.symbol,
oldPrice,
newPrice: price,
change: price - oldPrice,
changePercent: ((price - oldPrice) / oldPrice * 100).toFixed(2)
});
}
}
// Stock observers
const priceDisplay = (data) => {
console.log(`Display: ${data.symbol} $${data.newPrice} (${data.changePercent}%)`);
};
const priceAlert = (data) => {
if (Math.abs(data.changePercent) > 5) {
console.log(`ALERT: ${data.symbol} changed by ${data.changePercent}%!`);
}
};
const tradeBot = (data) => {
if (data.changePercent < -3) {
console.log(`Bot: Buying ${data.symbol} at $${data.newPrice}`);
} else if (data.changePercent > 3) {
console.log(`Bot: Selling ${data.symbol} at $${data.newPrice}`);
}
};
// Usage
console.log('\n--- Stock Market Observer ---');
const appleStock = new StockPrice('AAPL', 150);
// Subscribe to price changes
appleStock.on('price-changed', priceDisplay);
appleStock.on('price-changed', priceAlert);
appleStock.on('price-changed', tradeBot);
// Simulate price changes
appleStock.setPrice(152);
appleStock.setPrice(145);
appleStock.setPrice(160);
appleStock.setPrice(155);
// Model-View Pattern Example
class Model {
constructor() {
this.observers = [];
this.data = {};
}
subscribe(observer) {
this.observers.push(observer);
}
notify(change) {
this.observers.forEach(observer => observer.update(change));
}
set(key, value) {
const oldValue = this.data[key];
this.data[key] = value;
this.notify({ key, oldValue, newValue: value });
}
get(key) {
return this.data[key];
}
}
class View {
constructor(name, model) {
this.name = name;
this.model = model;
this.model.subscribe(this);
}
update(change) {
console.log(`${this.name} updating: ${change.key} changed from ${change.oldValue} to ${change.newValue}`);
this.render();
}
render() {
console.log(`${this.name} rendered with latest data`);
}
}
// Usage
console.log('\n--- Model-View Observer ---');
const userModel = new Model();
const profileView = new View('ProfileView', userModel);
const headerView = new View('HeaderView', userModel);
userModel.set('username', 'john_doe');
userModel.set('email', 'john@example.com');
Quick Facts
- Category
- Behavioral
- Common Use Cases
- Communication patterns, algorithms