-
Notifications
You must be signed in to change notification settings - Fork 0
/
ObjectPool.cs
93 lines (79 loc) · 2.55 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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Text;
namespace ObjectPool
{
/*
* Интерфейс для обьектов пула, которые
* при завершении работы могут быть
* возвращены в исходное состояние для
* переиспользования
*/
public interface IPoolable
{
void ResetState();
}
/*
* Интерфейс для создания обьектов
*/
public interface IPoolObjectCreator<T>
{
T Create();
}
/*
* Класс для создания екземпляров с
* помощью конструктора без параметров
*/
public class DefaultObjectCreator<T>: IPoolObjectCreator<T> where T: class, new()
{
T IPoolObjectCreator<T>.Create() {
return new T();
}
}
public class ObjectPool<T> where T : class, IPoolable
{
private readonly ConcurrentBag<T> _container = new ConcurrentBag<T>();
private readonly IPoolObjectCreator<T> _objectCreator;
public int Count { get { return _container.Count; } }
public ObjectPool(IPoolObjectCreator<T> creator)
{
if (creator == null) {
throw new ArgumentNullException("Creator == null");
}
this._objectCreator = creator;
}
public T GetObject()
{
T obj;
// TryTake - пытается удалить и вернуть объект из коллекции
if (this._container.TryTake(out obj)) {
return obj;
}
return this._objectCreator.Create();
}
public void ReturnObject(ref T obj)
{
obj.ResetState();
this._container.Add(obj);
obj = null;
}
}
public class SomeObject : IPoolable
{
private int _id { get; set; }
public int Index { get; set; }
public SomeObject()
{
var random = new Random();
this._id = random.Next(0, 1000);
Console.WriteLine("SomeObject#" + this._id.ToString() + " constructor");
this.Index = -1;
}
void IPoolable.ResetState()
{
Console.WriteLine("SomeObject#" + this._id.ToString() + " reset state");
this.Index = -1;
}
}
}