对象池简单实现

实现了一个简单的对象池,方便在对象数量不多的情况下复用对象:

//size为对象池最大对象数量,fCreate为对象的构造函数
//返回值是一个包含get方法的对象,本质是特定对象的objectPool
function objectPoolFactory(size,fCreate){
    var pool = [];

    function get(){
        var res == null;
        var noUses = pool.filter(function(item){
            return item.inUse === false;
        });
        if(noUses && noUses.length){
            noUses[0].inUse = true;
            res = noUses[0];
        }
        else{
            if(pool.length < size){
                res = fCreate(arguments);
                pool.push(res);
            }
        }
        return res;
    }

    return {
        get: get
    }
}
原文地址:https://www.cnblogs.com/mengff/p/9210009.html