Skip to content

Instantly share code, notes, and snippets.

@hulefei
Created September 7, 2017 03:02
Show Gist options
  • Save hulefei/5573875d50eb2ef5a064f214656d35f2 to your computer and use it in GitHub Desktop.
Save hulefei/5573875d50eb2ef5a064f214656d35f2 to your computer and use it in GitHub Desktop.
using System;
using System.Collections;
using System.Collections.Generic;
public class ObjectPool<T> where T : class {
private readonly Func<T> _objectFactory;
private readonly Queue<T> _queue = new Queue<T>();
/// <summary>
/// 对象池
/// </summary>
/// <param name="objectFactory">构造缓存对象的函数</param>
public ObjectPool(Func<T> objectFactory) {
_objectFactory = objectFactory;
}
/// <summary>
/// 构造指定数量的对象
/// </summary>
/// <param name="count">数量</param>
public void Allocate(int count) {
for (int i = 0; i < count; i++) {
_queue.Enqueue (_objectFactory ());
}
}
/// <summary>
/// 缓存一个对象
/// </summary>
/// <param name="obj">对象</param>
void Enqueue(T obj) {
_queue.Enqueue(obj);
}
/// <summary>
/// 获取一个对象
/// </summary>
/// <returns>对象</returns>
public T BorrowObject() {
T obj;
if (_queue.Count == 0) {
obj = _objectFactory ();
//_queue.Enqueue (obj);
} else {
obj = _queue.Dequeue();
if (obj == null) {
obj = _objectFactory ();
//_queue.Enqueue(obj);
}
}
return obj;
}
/// <summary>
/// 返还一个对象
/// </summary>
/// <returns>对象</returns>
public void ReturnObject(ref T obj) {
if (obj != null) {
_queue.Enqueue(obj);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment