对象池

代码

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
public static class RefreshDataPool<T> where T : RefreshData<T>, new()
{
private static readonly List<T> pool = new List<T>();

public static T Get()
{
lock (pool) // 使用锁来确保线程安全(如果这是多线程环境的话)
{
if (pool.Count > 0)
{
// 假设我们总是返回列表中的最后一个对象,并移除它以供重用
// 注意:这可能会导致对象重用顺序的问题,您可能需要根据实际情况调整
T obj = pool[pool.Count - 1];
pool.RemoveAt(pool.Count - 1);
return obj;
}

// 如果没有可用的对象,则创建一个新的对象
return new T();
}
}

public static void Push(T obj)
{
pool.Add(obj);
}
}

泛型方法参数

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
 public interface IRefresh
{
/// <summary>
/// 页面数据刷新
/// </summary>
void Refresh<T>(T data) where T : RefreshData<T>, new();
}

public abstract class RefreshDataBase
{
}

public class RefreshData<T> : RefreshDataBase, IDisposable where T : RefreshData<T>, new()
{
/// <summary>
/// 使用完成后记得释放
/// </summary>
public void Dispose()
{
RefreshDataPool<T>.Push((T)this);
}

/// <summary>
/// 获取事件
/// </summary>
/// <returns></returns>
public static T Get()
{
return RefreshDataPool<T>.Get();
}
}

/// <summary>
/// 后台给前台UI传递数据用
/// </summary>
public class StatusBarInfo : RefreshData<StatusBarInfo>
{
public FunctionBarType type;

//需要对下列数据进行的调整
public List<(FunctionBarData, FunctionBarOperationType)> operations = new();
}

//实现IRefresh接口的方法
public void Refresh<T>(T data) where T : RefreshData<T>, new()
{
var info = data as ItemRefreshData;
if (info.type == FunctionBarOperationType.Delete)
{
Destroy(this);
}
else
{
this.data = info.data;
_itemName.text = this.data.itemName;
}
}