-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathObjectPool.cs
78 lines (64 loc) · 1.97 KB
/
ObjectPool.cs
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
71
72
73
74
75
76
77
78
using System.Collections.Generic;
namespace ZUtils.ObjectPool
{
public delegate void OnReturned(IPooledObject caller);
public class ObjectPool<T> where T : class, IPooledObject
{
public delegate void OnChanged(ObjectPool<T> caller);
public event OnChanged Changed;
public List<T> Spawned { get; }
private readonly IPooledObjectFactory<T> objectFactory;
private readonly Stack<T> free;
public ObjectPool(IPooledObjectFactory<T> objectFactory)
{
this.objectFactory = objectFactory;
free = new Stack<T>();
Spawned = new List<T>();
}
public T Get()
{
T spawnedObject = free.Count == 0 ? objectFactory.Create() : free.Pop();
spawnedObject.Returned += SpawnedObjectOnReturned;
spawnedObject.OnBeforeSpawn();
Spawned.Add(spawnedObject);
Changed?.Invoke(this);
return spawnedObject;
}
private void SpawnedObjectOnReturned(IPooledObject pooledObject)
{
var tObject = pooledObject as T;
if (free.Contains(tObject))
return;
pooledObject.Returned -= SpawnedObjectOnReturned;
pooledObject.OnBeforeDespawn();
free.Push(tObject);
Spawned.Remove(tObject);
Changed?.Invoke(this);
}
}
public interface IPooledObject
{
event OnReturned Returned;
void Return();
void OnBeforeSpawn();
void OnBeforeDespawn();
}
public abstract class PooledObject : IPooledObject
{
public event OnReturned Returned;
public void Return()
{
Returned?.Invoke(this);
}
public virtual void OnBeforeSpawn()
{
}
public virtual void OnBeforeDespawn()
{
}
}
public interface IPooledObjectFactory<out T> where T : class, IPooledObject
{
T Create();
}
}