JavaScript模仿Apache的ObjectPool
2010-09-14 13:22:01 来源:WEB开发网在网上看到了有些同志提到了为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;
}
Tags:JavaScript 模仿 Apache
编辑录入:爽爽 [复制链接] [打 印]- ››JavaScript拖拽原理的实现
- ››javascript事件列表解说
- ››Javascript代码优化工具UglifyJS
- ››JavaScript Confirm 失效的解决办法
- ››Apache添加mod_aspdotnet.so支持ASP.NET配置指南
- ››JavaScript页面内拖拽原理分析
- ››javascript中select的常用操作
- ››javascript+css无刷新实现页面样式的更换
- ››javascript 摘记一
- ››Apache中改变php.ini的路径
- ››JavaScript alert()函数详细使用说明
- ››Apache2.2与Tomcat6整合及虚拟主机配置
更多精彩
赞助商链接