/
index.ts
61 lines (50 loc) · 1.38 KB
/
index.ts
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
// https://en.wikipedia.org/wiki/Flyweight_pattern
namespace FlyweightPattern {
interface IFlyweight {
code: number;
}
class Flyweight implements IFlyweight {
code: number;
constructor(code: number) {
this.code = code;
}
}
class FlyweightFactory {
static flyweights: { [id: number]: Flyweight } = {};
static getFlyweight(code: number): Flyweight {
if (!(code in FlyweightFactory.flyweights)) {
FlyweightFactory.flyweights[code] = new Flyweight(code);
}
return FlyweightFactory.flyweights[code];
}
static getCount(): number {
return Object.keys(FlyweightFactory.flyweights).length;
}
}
class AppContext {
private codes: number[] = [];
constructor(codes: string) {
for (let i = 0; i < codes.length; i++) {
this.codes.push(codes.charCodeAt(i));
}
}
output() {
let ret = "";
this.codes.forEach((c) => {
ret = ret + String.fromCharCode(FlyweightFactory.getFlyweight(c).code);
});
return ret;
}
}
// Client code
const context = new AppContext("abracadabra");
console.log(context.output());
console.log(`abracadabra has ${"abracadabra".length} letters`);
console.log(`FlyweightFactory has ${FlyweightFactory.getCount()} flyweights`);
// Output
/*
abracadabra
abracadabra has 11 letters
FlyweightFactory has 5 flyweights
*/
}