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 判断浏览器是否支持SVG方法
- ››apache设置域名绑定 以及绑定不起作用的排查
- ››javascript自动改变文字大小和颜色的效果
- ››apache rewrite将指定URL转向指定的几个服务器
- ››Javascript中产生固定结果函数的优化
- ››javascript 系统文件夹文件操作
- ››Javascript 遮罩层和加载效果
- ››javascript创建二维码(Table/Canvas两种方式)
- ››JavaScript定时器详解
- ››javascript中可以直接写php代码
- ››javascript 按回车键相应按钮提交事件
更多精彩
赞助商链接