什么是享元模式

享元模式(Flyweight Pattern)主要用于减少创建对象的数量,以减少内存占用和提高性能。这种类型的设计模式属于结构型模式,它提供了减少对象数量从而改善应用所需的对象结构的方式。

享元模式尝试重用现有的同类对象,如果未找到匹配的对象,则创建新对象。

面向对象例子:

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
class Flyweight{
constructor() {
this.divPool = [];
}

createDiv(text, parent) {
if (this.divPool.length > 0) {
console.log(`get from pool, pool count:${this.divPool.length}`);
let div = this.divPool.shift();
div.innerText = text;
parent.appendChild(div);
return div;
} else {
console.log(`create a new div, because pool count:${this.divPool.length}`);
let div = document.createElement('div');
div.innerText = text;
parent.appendChild(div);
return div;
}
}

removeDiv(node, parent) {
parent.removeChild(node);
this.recover(node);
console.log(`when ui remove div, restore this div, now pool has: ${this.divPool.length}`);
}

recover(node) {
this.divPool.push(node);
}
}

函数式例子:

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
(function () {

var circleFactory = (function () {
var circlePool = [];
var parent = document.querySelector('.flyweight-body');
return {
create: function () {
if (circlePool.length !== 0) {
return circlePool.shift();
} else {
var div = document.createElement('div');
div.setAttribute('class', 'flyweight-child');
parent.appendChild(div);
return div;
}
},
recover: function (dom) {
return circlePool.push(dom);
},
remove: function (oldPool) {
for (var i = 0; i < oldPool.length; i++) {
parent.removeChild(oldPool[i]);
}
}
}
})();

var renderCircle = (function () {
var circlePool = [];
return function (number) {
console.log('length: ' + circlePool.length);
for (var j = 0; j < number.length; j++) {
circleFactory.recover(circlePool.pop());
circlePool.length = circlePool.length - 1;
}
console.log('length: ' + circlePool.length);
circleFactory.remove(circlePool);
circlePool = [];
for (var i = 0; i < number; i++) {
var circle = circleFactory.create();
circle.style.left = Math.random() * 700 + 'px';
circle.style.top = Math.random() * 400 + 'px';
circlePool.push(circle);
}
}
})();

var init = function () {
Event.listen('draw-circle', function (args) {
var number = Number(args.number);
console.log(number);
renderCircle(number);
});
};

init();

})();