简易对象池
using System;
using System.Collections.Generic;
using UnityEngine;
/*
使用对象池,解决两个问题
1. new对象的时候的内存开销
2. 减少Object.Instaniate是内部序列化和反序列化而造成的CPU消耗
参考文献:http://gpp.tkchu.me/object-pool.html
*/
namespace QFramework
{
public interface IPool<T>
{
T Allocate();
bool Recycle(T obj);
}
public interface IObjectFactory<T>
{
T Create();
}
public abstract class Pool<T> : IPool<T>
{
//获取缓存的对象数量
public int Curcount
{
get
{
return mCacheStack.Count;
}
}
//工厂
protected IObjectFactory<T> mFactory;
//缓存
protected Stack<T> mCacheStack = new Stack<T>();
protected int mMxaCount = 5;
public virtual T Allocate()
{
return mCacheStack.Count == 0 ? mFactory.Create() : mCacheStack.Pop();
}
public abstract bool Recycle(T obj);
}
public class CustomObjectFactory<T> : IObjectFactory<T>
{
public CustomObjectFactory(Func<T> factoryMethod)
{
mFactoryMethod = factoryMethod;
}
protected Func<T> mFactoryMethod;
public T Create()
{
return mFactoryMethod();
}
}
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)
{
if (mResetMethod != null)
{
mResetMethod(obj);
}
mCacheStack.Push(obj);
return true;
}
}
}