C# 对象池代码示例

对象池代码示例
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ClassObjectPool<T> where T:class,new()
{
    //对象池
    protected Stack<T> pool = new Stack<T>();
    //对象池大小,超过则回收
    protected int maxCount = 0;
    //没有回收的对象个数
    protected int noRecycleCount = 0;

    public ClassObjectPool(int max)
    {
        maxCount = max;
        for (int i = 0; i < maxCount; i++)
        {
            pool.Push(new T());
        }
    }

    /// <summary>
    /// 从对象池中取出对象
    /// </summary>
    /// <param name="force">是否强制生成</param>
    /// <returns></returns>
    public T Get(bool force)
    {
        T t = null;
        if (pool.Count > 0)
        {
            t = pool.Pop();
        }

        if (force&&t==null)
        {
            t = new T();
            noRecycleCount++;
        }

        return t;
    }
    /// <summary>
    /// 回收对象,放进池中
    /// </summary>
    /// <param name="t">回收对象</param>
    /// <returns></returns>
    public bool Recycle(T t)
    {
        if (t == null)
        {
            return false;
        }

        noRecycleCount--;

        if (pool.Count > maxCount && maxCount > 0)
        {
            t = null;
            return false;
        }

        pool.Push(t);
        return true;

    }
    
}

很简答的代码啦,主要就是Get和Recycle两个函数用来获取和回收对象。

猜你喜欢

转载自blog.csdn.net/u013774978/article/details/135246869