-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathPool.cs
50 lines (40 loc) · 1.01 KB
/
Pool.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
namespace Pool {
using System;
using System.Collections;
using System.Collections.Generic;
public class Pool<T> : IEnumerable where T : IResettable {
public List<T> members = new List<T>();
public HashSet<T> unavailable = new HashSet<T>();
IFactory<T> factory;
public Pool(IFactory<T> factory) : this(factory, 5) { }
public Pool(IFactory<T> factory, int poolSize) {
this.factory = factory;
for(int i = 0; i < poolSize; i++) {
Create();
}
}
public T Allocate() {
for(int i = 0; i < members.Count; i++) {
if(!unavailable.Contains(members[i])) {
unavailable.Add(members[i]);
return members[i];
}
}
T newMember = Create();
unavailable.Add(newMember);
return newMember;
}
public void Release(T member) {
member.Reset();
unavailable.Remove(member);
}
T Create() {
T member = factory.Create();
members.Add(member);
return member;
}
IEnumerator IEnumerable.GetEnumerator() {
return (IEnumerator<T>)members.GetEnumerator();
}
}
}