Skip to content

Instantly share code, notes, and snippets.

@linx4200
Created May 12, 2018 12:55
Show Gist options
  • Save linx4200/ccf95ad967305e2ef49b72435063944f to your computer and use it in GitHub Desktop.
Save linx4200/ccf95ad967305e2ef49b72435063944f to your computer and use it in GitHub Desktop.
享元模式,共享对象,减少内存消耗
const flyweight = () => {
// 已创建的元素
const created = [];
// 这个例子是共享 dom 元素
function create () {
const dom = document.createElement('div');
document.getElementById('container').appendChild(dom);
created.push(dom);
return dom;
}
return {
getDiv(){
if(create.length < 5) {
return create();
} else {
const div = created.shift();
created.push(div);
return div;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment