public abstract class Pool<T> : IPool<T> { #region ICountObserverable /// <summary> /// Gets the current count. /// </summary> /// <value>The current count.</value> public int CurCount { get { return mCacheStack.Count; } } #endregion
protected IObjectFactory<T> mFactory;
protected Stack<T> mCacheStack = new Stack<T>();
/// <summary> /// default is 5 /// </summary> protected int mMaxCount = 5;
public virtual T Allocate() { return mCacheStack.Count == 0 ? mFactory.Create() : mCacheStack.Pop(); }
public abstract bool Recycle(T obj); }
对象池实现
首先要实现一个对象的创建器,代码如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
using System;
public class CustomObjectFactory<T> : IObjectFactory<T> { public CustomObjectFactory(Func<T> factoryMethod) { mFactoryMethod = factoryMethod; }
/// <summary> /// unsafe but fast /// </summary> /// <typeparam name="T"></typeparam> public class SimpleObjectPool<T> : Pool<T> { readonly Action<T> mResetMethod;
public SimpleObjectPool(Func<T> factoryMethod, Action<T> resetMethod = null,int initCount = 0) { mFactory = new CustomObjectFactory<T>(factoryMethod); mResetMethod = resetMethod;
for (int i = 0; i < initCount; i++) { mCacheStack.Push(mFactory.Create()); } }