diff options
author | chai <215380520@qq.com> | 2023-05-16 16:03:51 +0800 |
---|---|---|
committer | chai <215380520@qq.com> | 2023-05-16 16:03:51 +0800 |
commit | 2afbb545027568fccc85853e18af02a7c6b2929e (patch) | |
tree | 3827873af133fe9f81041e4babbfd0d54a53f9d1 /WorldlineKeepers/Assets/Scripts/Tools/Recycle.cs | |
parent | 88f739ea0f3440152082f34707e79328a71aabed (diff) |
*misc
Diffstat (limited to 'WorldlineKeepers/Assets/Scripts/Tools/Recycle.cs')
-rw-r--r-- | WorldlineKeepers/Assets/Scripts/Tools/Recycle.cs | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/WorldlineKeepers/Assets/Scripts/Tools/Recycle.cs b/WorldlineKeepers/Assets/Scripts/Tools/Recycle.cs new file mode 100644 index 0000000..a53289f --- /dev/null +++ b/WorldlineKeepers/Assets/Scripts/Tools/Recycle.cs @@ -0,0 +1,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; + } + + } +} |