下午不知道哪根筋不对劲了,突然去看看了最简单的DesignPattern之一的Singleton模式.看到了以前没有注意的一句话:只有一个实例只是最基本应用.在对象池中则要求多个实例.于是关于了一下对象池的实现.看了半天,好像多数的实现都是:http://blog.csdn.net/teddyma/archive/2006/01/11/4605987.aspx 这个版本的.看了会感觉这种简单的东西应该代码尽量简单才好.于是写了以下的版本.有什么问题,请大家指正.
using System;
using System.Collections;
using System.Diagnostics;
namespace DesignParttenProtype.Singleton.ObjectPool
{
publicclass ObjectPoolHelper<T>
{
privatestaticvolatile ObjectPoolHelper<T> _instance;
privatestaticobject lockHelper =newobject();
Queue _queue =new Queue();
private ObjectPoolHelper(int poolSize)
{
while (poolSize >0)
{
poolSize--;
_queue.Enqueue(Activator.CreateInstance<T>());
// Thread.Sleep(1000);
Debug.WriteLine("Add An Object Into ObjectPool Done!");
}
}
///<summary>
/// GetInstance
///</summary>
///<param name="poolSize"></param>
///<returns></returns>
publicstatic ObjectPoolHelper<T> GetSingletonInstance(int poolSize)
{
if (_instance ==null)
{
lock (lockHelper)
{
if (_instance ==null)
{
_instance =new ObjectPoolHelper<T>(poolSize);
}
}
}
return _instance;
}
///<summary>
/// Draw
///</summary>
///<returns></returns>
public T Draw()
{
T obj;
if (_queue.Count >0)
{
obj = (T)_queue.Dequeue();
Debug.WriteLine("Get An Object From Pool.");
}
else
{
obj = Activator.CreateInstance<T>();
Debug.WriteLine("Get New Object");
}
return obj;
}
///<summary>
/// Release
///</summary>
///<param name="type"></param>
publicvoid Release(T type)
{
if (type !=null)
{
_queue.Enqueue(type);
}
}
///<summary>
/// RemoveAll
///</summary>
publicvoid RemoveAll()
{
_queue.Clear();
}
}
}
using System.Collections;
using System.Diagnostics;
namespace DesignParttenProtype.Singleton.ObjectPool
{
publicclass ObjectPoolHelper<T>
{
privatestaticvolatile ObjectPoolHelper<T> _instance;
privatestaticobject lockHelper =newobject();
Queue _queue =new Queue();
private ObjectPoolHelper(int poolSize)
{
while (poolSize >0)
{
poolSize--;
_queue.Enqueue(Activator.CreateInstance<T>());
// Thread.Sleep(1000);
Debug.WriteLine("Add An Object Into ObjectPool Done!");
}
}
///<summary>
/// GetInstance
///</summary>
///<param name="poolSize"></param>
///<returns></returns>
publicstatic ObjectPoolHelper<T> GetSingletonInstance(int poolSize)
{
if (_instance ==null)
{
lock (lockHelper)
{
if (_instance ==null)
{
_instance =new ObjectPoolHelper<T>(poolSize);
}
}
}
return _instance;
}
///<summary>
/// Draw
///</summary>
///<returns></returns>
public T Draw()
{
T obj;
if (_queue.Count >0)
{
obj = (T)_queue.Dequeue();
Debug.WriteLine("Get An Object From Pool.");
}
else
{
obj = Activator.CreateInstance<T>();
Debug.WriteLine("Get New Object");
}
return obj;
}
///<summary>
/// Release
///</summary>
///<param name="type"></param>
publicvoid Release(T type)
{
if (type !=null)
{
_queue.Enqueue(type);
}
}
///<summary>
/// RemoveAll
///</summary>
publicvoid RemoveAll()
{
_queue.Clear();
}
}
}