using System;
using System.Collections.Generic;
public class ObjectPool<T> where T:class
{
//堆栈
private readonly Stack<T> m_stack;
//事件
private readonly Func<T> m_ActionOnCreate;
private readonly Action<T> m_ActionOnGet;
private readonly Action<T> m_ActionOnRelease;
//构造函数
public ObjectPool(Func<T> actionOnCreate, Action<T> actionOnGet, Action<T> actionOnRelease)
{
m_stack = new Stack<T>();
m_ActionOnCreate = actionOnCreate;
m_ActionOnGet = actionOnGet;
m_ActionOnRelease = actionOnRelease;
}
//获取接口
public T Get()
{
T obj;
if(m_stack.Count == 0)
{
//执行构建操作
obj = m_ActionOnCreate();
}
else
{
obj = m_stack.Pop();
}
//执行回调
if(m_AcitonOnGet != null)
{
m_ActionOnGet(obj);
}
return obj;
}
//释放接口
public void Release(T obj)
{
if(m_ActionOnRelease != null)
{
m_ActionOnRelease(obj);
}
m_stack.Push(obj);
}
//clear接口
public void Clear()
{
m_stack.Clear();
}
}
网友评论