单例基类 与 类对象池

单例基类:

    public class SinglentonBaseClass<T> where T : new()
    {
        private static T m_Instance;
        public static T Instance
        {
            get {
                if (m_Instance == null)
                {
                    m_Instance = new T();
                }
                return m_Instance;
            }
        }
    }

类对象池:

 /* 类对象池管理器 */
    public class ClassObjectPoolManager:SinglentonBaseClass<ClassObjectPoolManager>
    {
        //  类对象池缓存区
        protected Dictionary<Type, object> m_ClassPoolDic = new Dictionary<Type, object>();

        //  类对象池创建
        public ClassObjectPool<T> GetOrCreatClassPool<T>(int _maxcount) where T : class, new()
        {
            Type type = typeof(T);
            if (!m_ClassPoolDic.TryGetValue(type, out object _outObj) || _outObj == null)
            {
                ClassObjectPool<T> _newPool = new ClassObjectPool<T>(_maxcount);
                m_ClassPoolDic.Add(type, _newPool);
                return _newPool;
            }
            else
            {
                return _outObj as ClassObjectPool<T>;
            }
        }
    }

    /* 类对象池 */
    public class ClassObjectPool<T> where T : class , new()
    {
        //  基栈
        protected Stack<T> m_Pool = new Stack<T>();

        //  最大数量 (-1 == 无穷)
        protected int m_MaxCount = -1;

        //  未曾回收个数
        protected int m_UnRecoveredCount = 0;

        public ClassObjectPool(int _maxCount)
        {
            m_MaxCount = _maxCount;
            for (int i = 0; i < _maxCount; i++)
            {
                m_Pool.Push(new T());
            }    
        }

        //   取出
        public T Spawn(bool _forceToGet)
        {
            if (m_Pool.Count > 0)
            {
                T _t = m_Pool.Pop();
                if (_t == null)
                {
                    if (_forceToGet)
                    {
                        _t = new T();
                    }
                }
                m_UnRecoveredCount ++;
                return _t;
            }
            else
            {
                if (_forceToGet)
                {
                    T _t = new T();
                    m_UnRecoveredCount ++;
                    return _t;
                }
            }
            return null;
        }

        //   回收
        public bool Recycle(T _class)
        {
            if (_class == null)
            {
                return false;
            }
            m_UnRecoveredCount--;
            if (m_Pool.Count >= m_MaxCount && m_MaxCount != -1) 
            {
                _class = null;
                return false;
            }
            m_Pool.Push(_class);
            return true;
        }
    }

你可能感兴趣的:(C#)