Beispiel #1
0
        /// <summary>
        /// 获取实例,如果已取出的数量超出池子的容量将返回null
        /// </summary>
        /// <returns>对象实例</returns>
        public T GetObject()
        {
            if (_UsedPool.Count >= _Pool.RingSize)
            {
                return(null);
            }
            T result;

            if (!_Pool.TryDequeue(out result))
            {
                if (_Template == null)
                {
                    result = new T();
                }
                else
                {
                    result = CloneTools.DeepCopy(_Template);
                }
            }
            _UsedPool.Add(result);
            return(result);
        }
Beispiel #2
0
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="poolSize">池子最大容量</param>
        /// <param name="fill">初始化时是否填满池子</param>
        /// <param name="template">克隆模板(模板不为空时将自动调用CloneTools.DeepCopy进行拷贝)</param>
        public ObjectPool(int poolSize, bool fill = false, T template = null)
        {
            _Template = template;
            _Pool     = new RingQueue <T>(poolSize);
            if (fill)
            {
                if (template == null)
                {
                    for (int i = 0; i < poolSize; i++)
                    {
                        _Pool.Enqueue(new T());
                    }
                }
                else
                {
                    for (int i = 0; i < poolSize; i++)
                    {
                        _Pool.Enqueue(CloneTools.DeepCopy(template));
                    }
                }
            }

            _UsedPool = new List <T>(_Pool.RingSize);
        }