Skip to content
本文总阅读量

对象池模式

HTML

HTML
<html>
    <body>
        <button><button>
    </body>
</html>

JS

JS
var  objectPoolFactory  =  function  (createObjFn)  {
    var  objectPool  =  []
    return  {
        create:  function  ()  {
            var  obj  =  objectPool.length  ===  0  ?
            createObjFn.apply(this,  arguments)  :  objectPool.shift()
            return  obj
        },
        recove:  function  (obj)  {
        objectPool.push(obj)
        }
    }
}


  
var  iframeFactory  =  objectPoolFactory(function  ()  {
    var  iframe  =  document.createElement("IFRAME");
    document.body.appendChild(iframe);
    iframe.onload  =  function  ()  {
        iframe.onload  =  null  // 防止重复
        iframeFactory.recove(iframe)  // 回收iframe节点
    }
    return  iframe
})


var  iframe1  =  iframeFactory.create()
iframe1.src  =  'https://www.w3school.com.cn';
var  iframe2  =  iframeFactory.create();
iframe2.src  =  'http://QQ.com';


setTimeout(function  ()  {
    var  iframe3  =  iframeFactory.create();
    iframe3.src  =  'http://163.com';
},  3000);

输出