/
flyweight.js
52 lines (37 loc) · 1.45 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
(function(exports){
var flyweightFactory = new FlyweightFactory();
exports.add = function(userContextJson){
return flyweightFactory.add(userContextJson);
};
exports.get = function(uniqueValue){
return flyweightFactory.get(uniqueValue);
};
exports.count = function(){
return flyweightFactory.count();
};
function Flyweight(context) {
this.context = context;
};
function FlyweightFactory(){
var flyweights = {},
numOfFlyweights = 0;
return {
add: function (userContextJson) {
var contextJson = userContextJson || {},
value = contextJson.value || JSON.stringify(contextJson)
key = value;
if (!flyweights[key]) {
flyweights[key] = new Flyweight(contextJson);
numOfFlyweights++;
}
return flyweights[key].context;
},
get: function (key) {
return flyweights[key].context;
},
count: function () {
return numOfFlyweights;
}
};
}
}(typeof exports === 'undefined' ? this.flyweightPattern = {} : exports));