Repository navigation
Expand file tree
/
Copy pathflyweight.html
More file actions
114 lines (99 loc) · 2.95 KB
/
Copy pathflyweight.html
File metadata and controls
114 lines (99 loc) · 2.95 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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Flyweight Design Pattern Example</title>
</head>
<body>
<h1>Flyweight Design Pattern Example</h1>
<button id="runButton">Run Flyweight</button>
<div id="output"></div>
<script>
// Utility function to simulate interface implementation
const implementsInterface = (obj, iface) => {
for (let method of iface) {
if (typeof obj[method] !== 'function') {
return false;
}
}
return true;
};
// CoffeeOrder interface
const CoffeeOrder = ['serveCoffee', 'getFlavor'];
class CoffeeFlavor {
constructor(newFlavor) {
this.flavor = newFlavor;
}
getFlavor() {
return this.flavor;
}
serveCoffee(context) {
console.log(
`Serving Coffee flavor ${this.flavor} to table ${context.getTable()}`
);
}
}
const CoffeeOrderContext = (tableNumber) => ({
getTable() {
return tableNumber;
},
});
class CoffeeFlavorFactory {
constructor() {
this.flavors = {};
this.length = 0;
}
getCoffeeFlavor(flavorName) {
let flavor = this.flavors[flavorName];
if (!flavor) {
flavor = new CoffeeFlavor(flavorName);
if (implementsInterface(flavor, CoffeeOrder)) {
this.flavors[flavorName] = flavor;
this.length++;
} else {
console.log(`Error: ${flavorName} does not implement the CoffeeOrder interface.`);
return null;
}
}
return flavor;
}
getTotalCoffeeFlavorsMade() {
return this.length;
}
}
// Button click event
const runButton = document.getElementById('runButton');
runButton.addEventListener('click', function () {
testFlyweight();
});
// Test Flyweight
function testFlyweight() {
const flavors = [];
const tables = [];
let ordersMade = 0;
const flavorFactory = new CoffeeFlavorFactory();
function takeOrders(flavorIn, table) {
const flavor = flavorFactory.getCoffeeFlavor(flavorIn);
if (flavor) {
flavors.push(flavor);
tables.push(CoffeeOrderContext(table));
ordersMade++;
}
}
// Place orders
takeOrders('Cappuccino', 2);
takeOrders('Latte', 4);
takeOrders('Espresso', 1);
takeOrders('Americano', 3);
// Serve orders
for (let i = 0; i < ordersMade; ++i) {
flavors[i].serveCoffee(tables[i]);
}
const output = document.getElementById('output');
output.innerHTML = `
<p><strong>Total CoffeeFlavor objects made:</strong> ${flavorFactory.getTotalCoffeeFlavorsMade()}</p>
`;
}
</script>
</body>
</html>