美文网首页
Unity 简单的缓存池

Unity 简单的缓存池

作者: UnityChan | 来源:发表于2020-01-15 09:36 被阅读0次
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();
    }
}

相关文章

网友评论

      本文标题:Unity 简单的缓存池

      本文链接:https://www.haomeiwen.com/subject/rjazactx.html