一点一点看 原理很简单 就不解释了
public interface IPool<T>
{
T Allocate();
bool Recycle(T obj);
}
public interface ICountObserveAble
{
int CurCount { get; }
}
public interface IObjectFactory<T>
{
T Create();
}
using System.Collections.Generic;
public abstract class Pool<T> : IPool<T>,ICountObserveAble
{
#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 readonly Stack<T> mCacheStack = new Stack<T>();
/// <summary>
/// default is 5
/// </summary>
protected int mMaxCount = 12;
public virtual T Allocate()
{
return mCacheStack.Count == 0
? mFactory.Create()
: mCacheStack.Pop();
}
public abstract bool Recycle(T obj);
}
using System;
public class CustomObjectFactory<T> : IObjectFactory<T>
{
public CustomObjectFactory(Func<T> factoryMethod)
{
mFactoryMethod = factoryMethod;
}
protected Func<T> mFactoryMethod;
public T Create()
{
return mFactoryMethod();
}
}
using System;
/// <summary>
/// Unity 游戏框架搭建 (十九) 简易对象池:http:///post/24/ 的例子
/// </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());
}
}
public override bool Recycle(T obj)
{
mResetMethod.InvokeGracefully(obj);
mCacheStack.Push(obj);
return true;
}
}
public class SimpleObjectPoolExample : MonoBehaviour
{
/// <summary>
///
/// </summary>
public class Fish
{
}
private void Start()
{
var fishPool = new SimpleObjectPool<Fish>(() => new Fish(), null, 100);
Log.I("fishPool.CurCount:{0}", fishPool.CurCount);
var fishOne = fishPool.Allocate();
Log.I("fishPool.CurCount:{0}", fishPool.CurCount);
fishPool.Recycle(fishOne);
Log.I("fishPool.CurCount:{0}", fishPool.CurCount);
for (int i = 0; i < 10; i++)
{
fishPool.Allocate();
}
Log.I("fishPool.CurCount:{0}", fishPool.CurCount);
}
}
IPool 接口 有 Allocate取出 Recycle放回
















