Created
May 12, 2018 12:55
-
-
Save linx4200/ccf95ad967305e2ef49b72435063944f to your computer and use it in GitHub Desktop.
享元模式,共享对象,减少内存消耗
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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