WEB开发网
开发学院网页设计JavaScript JavaScript模仿Apache的ObjectPool 阅读

JavaScript模仿Apache的ObjectPool

 2010-09-14 13:22:01 来源:WEB开发网   
核心提示:在网上看到了有些同志提到了为Ajax的XMLHttpRequest提供一个对象池,也读了他们给出的实现代码,JavaScript模仿Apache的ObjectPool,感觉不是特别理想,于是模仿apache的commons中的ObjectPool的思路写了一个简单的JavaScript版,用完记得一定要还哦!Objec

在网上看到了有些同志提到了为Ajax的XMLHttpRequest提供一个对象池,也读了他们给出的实现代码。感觉不是特别理想,于是模仿apache的commons中的ObjectPool的思路写了一个简单的JavaScript版。望指教:

function ObjectPool(poolableObjectFactory) {
  this._poolableObjectFactory = poolableObjectFactory;
  this._idlePool = [];
  this._activePool = [];
}
// 从对象池中租借一个对象,如果目前没有可用的空闲对象则通过poolableObjectFactory创建一个
// 既然是借的,用完记得一定要还哦!
ObjectPool.prototype.borrowObject = function() {
  var object = null;
  var idlePool = this._idlePool;
  var factory = this._poolableObjectFactory;
  if (idlePool.length > 0) {
    object = idlePool.pop();
  }
  else {
    object = factory.makeObject();
  }
  if (object != null) {
    this._activePool.push(object);
    if (factory.activateObject) {
      factory.activateObject(object);
    }
  }
  return object;
}
// 归还一个对象
ObjectPool.prototype.returnObject = function(object) {
  function indexOf(array, object) {
    for (var i = 0; i < array.length; i++) {
      if (array[i] == object) return i;
    }
    return -1;
  }
  if (object != null) {
    var activePool = this._activePool;
    var factory = this._poolableObjectFactory;    
    var i = indexOf(activePool, object);
    if (i < 0) return;    
    if (factory.passivateObject) {
      factory.passivateObject(object);
    }    
    activePool.splice(i, 1);
    this._idlePool.push(object);
  }
}
// 返回当前激活对象的个数
ObjectPool.prototype.getNumActive = function() {
  return this._activePool.length;
}
// 返回当前空闲对象的个数
ObjectPool.prototype.getNumIdle = function() {
  return this._idlePool.length;
}
// 销毁对象池及其中的所有对象
// 如果对象池中的对象需要析构。那么必须实现poolableObjectFactory中的destroyObject方法,同时保证ObjectPool的destroy方法在需要的时候被调用到(例如Window的unload事件中)。
ObjectPool.prototype.destroy = function() {
  var factory = this._poolableObjectFactory;
  function returnObject(object) {
    if (factory.passivateObject) {
      factory.passivateObject(object);
    }
  }
  function destroyObject(object) {
    if (factory.destroyObject) {
      factory.destroyObject(object);
    }
  }
var activePool = this._activePool;
  for (var i = 0; i < activePool.length; i++) {
    var object = activePool[i];
    returnObject(object);
    destroyObject(object);
  }
  var idlePool = this._idlePool;
  for (var i = 0; i < idlePool.length; i++) {
    var object = idlePool[i];
    destroyObject(object);
  }
  this._idlePool = null;
  this._activePool = null;
  this._poolableObjectFactory = null;
}

1 2 3  下一页

Tags:JavaScript 模仿 Apache

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接