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

JavaScript模仿Apache的ObjectPool

 2010-09-14 13:22:01 来源:WEB开发网   
核心提示: 最后附上jsUnit的测试用例: function test_pool() {var factory = {counter: 0,makeObject: function() {return {id: ++ this.counter};},activateObject: function(

最后附上jsUnit的测试用例:

function test_pool() {
  var factory = {
    counter: 0,
makeObject: function() {
      return {id: ++ this.counter};      
    },
activateObject: function(object) {
      object.activated = true;
    },
passivateObject: function(object) {
      object.activated = false;      
    },
destroyObject: function(object) {
      object.destroyed = true;      
    }
  };
  //  
  var pool = new ObjectPool(factory);
  //
  // borrowObject object1
  var object1 = pool.borrowObject();
  assertEquals(object1.id, 1);
  assertTrue(object1.activated);
  assertEquals(factory.counter, 1);
  assertEquals(pool.getNumActive(), 1);
  assertEquals(pool.getNumIdle(), 0);
  //  
  // borrowObject object2
  var object2 = pool.borrowObject();
  assertEquals(object2.id, 2);
  assertTrue(object2.activated);
  assertEquals(factory.counter, 2);
  assertEquals(pool.getNumActive(), 2);
  assertEquals(pool.getNumIdle(), 0);
  //  
  // borrowObject object3
  var object3 = pool.borrowObject();
  assertEquals(object3.id, 3);
  assertTrue(object3.activated);
  assertEquals(factory.counter, 3);
  assertEquals(pool.getNumActive(), 3);
  assertEquals(pool.getNumIdle(), 0);
  //  
  // returnObject object2
  pool.returnObject(object2);
  assertFalse(object2.activated);
  assertEquals(factory.counter, 3);
  assertEquals(pool.getNumActive(), 2);
  assertEquals(pool.getNumIdle(), 1);
  //  
  // returnObject object3
  pool.returnObject(object3);
  assertFalse(object3.activated);
  assertEquals(pool.getNumActive(), 1);
  assertEquals(pool.getNumIdle(), 2);  
  //  
  // returnObject object1
  pool.returnObject(object1);
  assertFalse(object1.activated);
  assertEquals(pool.getNumActive(), 0);
  assertEquals(pool.getNumIdle(), 3);  
  //  
  // destroy the pool
  pool.destroy();
  assertTrue(object1.destroyed);
  assertTrue(object2.destroyed);
  assertTrue(object3.destroyed);
}

上一页  1 2 3 

Tags:JavaScript 模仿 Apache

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