forked from zoltantothcom/Design-Patterns-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbehavioral_observer.js
More file actions
95 lines (80 loc) · 1.77 KB
/
behavioral_observer.js
File metadata and controls
95 lines (80 loc) · 1.77 KB
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
const OBSERVER = {
id: 'observer',
name: 'Observer',
type: 'behavioral',
hint: 'A way of notifying change to a number of classes',
definition: `Define a one-to-many dependency between objects so that when one object changes state,
all its dependents are notified and updated automatically.`,
when: 'a change to one object requires changing others',
codeES5: `function Product() {
this.price = 0;
this.actions = [];
}
Product.prototype.setBasePrice = function(val) {
this.price = val;
this.notifyAll();
};
Product.prototype.register = function(observer) {
this.actions.push(observer);
};
Product.prototype.unregister = function(observer) {
this.actions.remove.filter(function(el) {
return el !== observer;
});
};
Product.prototype.notifyAll = function() {
return this.actions.forEach(
function(el) {
el.update(this);
}.bind(this)
);
};
var fees = {
update: function(product) {
product.price = product.price * 1.2;
}
};
var profit = {
update: function(product) {
product.price = product.price * 2;
}
};
module.exports = [Product, fees, profit];`,
codeES6: `class Product {
constructor() {
this.price = 0;
this.actions = [];
}
setBasePrice(val) {
this.price = val;
this.notifyAll();
}
register(observer) {
this.actions.push(observer);
}
unregister(observer) {
this.actions.remove.filter(function(el) {
return el !== observer;
});
}
notifyAll() {
return this.actions.forEach(
function(el) {
el.update(this);
}.bind(this)
);
}
}
class fees {
update(product) {
product.price = product.price * 1.2;
}
}
class profit {
update(product) {
product.price = product.price * 2;
}
}
export { Product, fees, profit };`
};
export default OBSERVER;