-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathDecoratorPattern.js
More file actions
57 lines (52 loc) · 1.59 KB
/
Copy pathDecoratorPattern.js
File metadata and controls
57 lines (52 loc) · 1.59 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
"use strict";
/**
* Decorator Pattern - Adding extra functionalities to an object without affecting
* its structure. Like the name suggests, this pattern is used to add additional
* features to an item. Similar to decorating a christmas tree, topping up with
* christmas lights and other ornaments to look better.
*
* Example - Your social network account might need certain membership addons to
* to get access to more information or functions. Purchasing the addons is one way
* to equip the membership with more addons but it comes with a cost. The membership
* fee may be increased. Decorator Pattern can be used in this scenario
*
*/
class Membership {
constructor(addons, cost) {
this.addons = addons;
this.cost = cost;
}
getAddons() {
return this.addons;
}
getCost() {
return this.cost;
}
}
let addOnPost = (membership) => {
let _getAddons = membership.getAddons();
membership.getAddons = () => {
let addons = _getAddons;
addons.push("CanPost")
return addons;
}
let _getCost = membership.getCost();
membership.getCost = () => {
return _getCost + 0.99;
}
}
let addOnAdmin = (membership) => {
let _getAddons = membership.getAddons();
membership.getAddons = () => {
let addons = _getAddons;
addons.push("IsAdmin");
return addons;
}
}
let jack001 = new Membership(["CanView"], 0.8);
console.log(jack001.getCost());
addOnPost(jack001);
console.log(jack001.getCost());
addOnAdmin(jack001);
console.log(jack001.getCost());
console.log(jack001.getAddons());