Unity 简单的缓存池

using System;
using System.Collections.Generic;

public class ObjectPool where T:class
{
   //堆栈
   private readonly Stack  m_stack;
   //事件
   private readonly Func   m_ActionOnCreate;
   private readonly Action m_ActionOnGet;
   private readonly Action m_ActionOnRelease;
   //构造函数
  public ObjectPool(Func actionOnCreate, Action actionOnGet, Action actionOnRelease)
    {
            m_stack             = new Stack();
            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();
    }
}

你可能感兴趣的:(Unity 简单的缓存池)