summaryrefslogtreecommitdiff
path: root/WorldlineKeepers/Assets/Scripts/Tools/Recycle.cs
blob: a53289f0bdd582139684dfa517004bbd8556a69c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
using System;
using System.Collections.Generic;

namespace WK
{

    /// <summary>
    /// 实现此接口重置回收对象的成员值
    /// </summary>
    public interface IRcycle
    {
        void Release();
    }

    public class Recycle<T> where T : IRcycle, new()
    {
        private List<T> cachedNodeList;
        private int maxCapacity;

        public Recycle(int initCapacity, int maxCapacity)
        {
            this.maxCapacity = maxCapacity;
            if (cachedNodeList == null)
            {
                cachedNodeList = new List<T>(initCapacity);
                for (int i = 0; i < initCapacity; ++i)
                {
                    cachedNodeList.Add(new T());
                }
            }
        }

        public T GetUnusedNode()
        {
            if (cachedNodeList.Count > 0)
            {
                // remove and return last node
                int i = cachedNodeList.Count - 1;
                T t = cachedNodeList[i];
                cachedNodeList.RemoveAt(i);
                return t;
            }
            return new T();
        }

        //回收对象并将原引用置为初始值(0或null)
        public bool ReleaseNode(ref T t)
        {
            if (t == null)
                return false;

            T refT = t;
            t = default(T);

            if (cachedNodeList.Count > maxCapacity)
                return false;

            if (cachedNodeList.Contains(refT))
            {
                LogHelper.LogError("重复回收");
                return false;
            }

            refT.Release();
            cachedNodeList.Add(refT);
            return true;
        }

    }
}