運用共享技術(shù)有效的支持大量的細(xì)粒度的對象溉贿,避免對象間擁有相同內(nèi)容造成多余的開銷
// 享元對象
var Flyweight = function () {
var created = [];
function create() {
var dom = document.createElement('div');
document.getElementById('container').appendChild(dom);
created.push(dom);
return dom;
}
return {
getDiv : function() {
if (created.length < 5) {
return create();
} else {
var div = created.shift();
created.push(div);
return div;
}
}
}
}();
// 實現(xiàn)需求
var paper = 0,
num = 5,
len = article.length;
for (var i=0; i<5; i++) {
if (article[i]) {
Flyweight.getDiv().innerHTML = article[i];
}
}
document.getElementById('next_page').onclick = function () {
if (article.length < 5) {
return
}
var n = ++paper * num % len,
j = 0;
for (; j < 5; j++) {
if (article[n + j]) {
Flyweight.getDiv().innerHTML = article[n + j];
} else if (article[n + j - len]) {
Flyweight.getDiv().innerHTML = article[n + j - len];
} else {
Flyweight.getDiv().innerHTML = "";
}
}
}