51代码网ORACLEMYSQLSQL SERVER其它数据库java/jspasp/asp.netC/C++/VC++APP应用其它语言服务器应用
您现在的位置: 51代码网 >> C >> 文章正文

怎么才能非常完善的测试一个对象池是的实现否是正确的

更新时间:2012-1-3:  来源:51代码网

问题是这样的:我用特殊方法实现了一个对象池,并且通过了简单的测试。怎么才能非常完善的测试一个对象池是的实现否是正确的。

为了方便讨论,先贴一个标准的对象池的实现代码,大家可以假设这个实现有缺陷,对其进行测试

using System;

namespace TEST
{
    public sealed class ObjectPool<T> : IPool<T>
        where T : class
    {

        private readonly Func<T> _creater = null;
        private readonly Action<T> _rester = null;
        private readonly T[] _objs = null;
        private readonly int _capcity;

        private int _remainer;

        public ObjectPool(int capcity, Func<T> creater = null, Action<T> rester = null)
        {
            _capcity = _remainer = capcity;
            _creater = creater;
            _rester = rester;
            _objs = new T[capcity];
            for (int i = 0; i < capcity; i++)
                _objs[i] = creater();

        }

        public int Capcity { get { return _capcity; } }
        public int Remainer { get { return _remainer; } }

        public T Fetch()
        {
            if (_remainer <= 0)
                throw new Exception();

            lock (_objs)
            {
                return _objs[--_remainer];
            }
        }
        public void Store(T obj)
        {
            if (_remainer >= _capcity)
                throw new Exception();

            if (_rester != null)
                _rester(obj);
            lock (_objs)
            {
                _objs[_remainer++] = obj;
            }
        }
    }
}
Func<T> creater = null

_objs[i] = creater();
--------------------------
creater 不能为null,为null要显式抛出 ArgumentException
=======================================================
if (_remainer <= 0)
  throw new Exception();
应该布尔值来区分,真要使用异常 也要有明确的提示信息。
===================================
lock 用的有问题
有很多现成的集合,例如 List<T>、LinkedList<T>、Queue<T>、Dictionary<K,T>、SortedList<K,T> 等等。不知道“对象池”有什么不一样的?最好你考虑兼容这些东西的一两个基础接口。

凭空出现一个东西,让别人来“非常完善的测试”,这就好像你说你连过葵花宝典,让别人都来“非常完善地”测试你,谁愿意呢?谁有你更知道葵花宝典是干什么用的呢?

赞助商链接
推荐文章
  • 此栏目下没有推荐文章
  • {
    设为首页 | 加入收藏 | 友情链接 | 网站地图 | 联系站长 |