-
Notifications
You must be signed in to change notification settings - Fork 74
/
Flyweight.js
71 lines (60 loc) · 1.89 KB
/
Flyweight.js
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
'use strict';
class FlyweightFactory {
constructor() {
this.flyweights = {};
console.log('FlyweightFactory Class created');
}
getFlyweight(key) {
console.log('FlyweightFactory.getFlyweight invoked');
if (this.flyweights[key]) {
return this.flyweights[key];
} else {
this.flyweights[key] = new ConcreteFlyweight(key);
return this.flyweights[key];
}
}
createGibberish(keys) {
console.log('FlyweightFactory.createGibberish invoked');
return new UnsharedConcreteFlyweight(keys, this);
}
}
class Flyweight {
constructor() {
console.log('Flyweight Class created');
}
operation(extrinsicState) {
console.log('Flyweight.operation invoked');
}
}
class ConcreteFlyweight extends Flyweight {
constructor(key) {
super();
this.intrinsicState = key;
console.log('ConcreteFlyweight Class created');
}
operation(extrinsicState) {
console.log('ConcreteFlyweight.operation invoked');
return extrinsicState + this.intrinsicState;
}
}
class UnsharedConcreteFlyweight extends Flyweight {
constructor(keys, flyweights) {
super();
this.flyweights = flyweights;
this.keys = keys;
console.log('UnsharedConcreteFlyweight Class created');
}
operation(extrinsicState) {
console.log('UnsharedConcreteFlyweight.operation invoked');
var key, word = '';
for (var i = 0; i < extrinsicState; i++) {
key = this.keys[Math.floor(Math.random() * (this.keys.length))];
word = this.flyweights.getFlyweight(key).operation(word);
}
console.log('UnsharedConcreteFlyweight Operation: ');
console.log(word);
}
}
var flyweights = new FlyweightFactory();
var gibberish = flyweights.createGibberish(['-', '+', '*']);
gibberish.operation(5);