forked from zoltantothcom/Design-Patterns-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructural_composite.js
More file actions
125 lines (106 loc) · 2.38 KB
/
structural_composite.js
File metadata and controls
125 lines (106 loc) · 2.38 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
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
const COMPOSITE = {
id: 'composite',
name: 'Composite',
type: 'structural',
hint: 'A tree structure of simple and composite objects',
definition: `Compose objects into tree structures to represent part-whole hierarchies.
Composite lets clients treat individual objects and compositions of objects uniformly.`,
when: `you want to represent hierarchies of objects`,
codeES5: `function EquipmentPattern(name) {
this.equipments = [];
this.name = name;
}
EquipmentPattern.prototype.add = function(equipment) {
this.equipments.push(equipment);
};
EquipmentPattern.prototype.getPrice = function() {
return this.equipments
.map(function(equipment) {
return equipment.getPrice();
})
.reduce(function(a, b) {
return a + b;
});
};
function Equipment() {}
Equipment.prototype.getPrice = function() {
return this.price;
};
// -- leafs
function FloppyDisk() {
this.name = 'Floppy Disk';
this.price = 70;
}
FloppyDisk.prototype = Object.create(Equipment.prototype);
function HardDrive() {
this.name = 'Hard Drive';
this.price = 250;
}
HardDrive.prototype = Object.create(Equipment.prototype);
function Memory() {
this.name = '8gb memomry';
this.price = 280;
}
Memory.prototype = Object.create(Equipment.prototype);
module.exports = [EquipmentPattern, FloppyDisk, HardDrive, Memory];`,
codeES6: `//Equipment
class Equipment {
getPrice() {
return this.price || 0;
}
getName() {
return this.name;
}
setName(name) {
this.name = name;
}
}
class Pattern extends Equipment {
constructor() {
super();
this.equipments = [];
}
add(equipment) {
this.equipments.push(equipment);
}
getPrice() {
return this.equipments
.map(equipment => {
return equipment.getPrice();
})
.reduce((a, b) => {
return a + b;
});
}
}
class Cabbinet extends Pattern {
constructor() {
super();
this.setName('cabbinet');
}
}
// --- leafs ---
class FloppyDisk extends Equipment {
constructor() {
super();
this.setName('Floppy Disk');
this.price = 70;
}
}
class HardDrive extends Equipment {
constructor() {
super();
this.setName('Hard Drive');
this.price = 250;
}
}
class Memory extends Equipment {
constructor() {
super();
this.setName('Memory');
this.price = 280;
}
}
export { Cabbinet, FloppyDisk, HardDrive, Memory };`
};
export default COMPOSITE;