Singleton模式 提供一种方法使得某一特定类型对象实例在全局范围内最多只能存在一个。该模式实际上可以被认为是对象池的一个特例,它提供了一个全局的存取点,以及注册、查找功能。其中注册和查找是相关联的。
Singleton Pattern实现的关键在于防止用户以其它任何方式创建对象,而只能用你所提供的方式。所有的构造函数必须被声明为私有的,而且必须至少声明一个构造函数。
public static class Singleton
{
public static ArrayList arrayList;
static Singleton()
{
//静态类只能由私有的静态构造函数,因为静态类不能被实例化
}
public static void Registry(IMyClass obj)
{
arrayList.Add(obj);
}
public static bool
LookUp(IMyClass obj)
{ //…
}
}
我测试了类的静态构造函数,它不但允许你实例化对象,同时更让你能够在调用静态方法做些初始化工作。但由于静态方法必须是无参数的,因此你也就不能重载静态构造函数,也就是说,静态构造函数只能存在一个单件模式样例
public class Singleton
{
static bool isRun = false;
Singleton() { }
public static Singleton getSingleton()
{
if (!isRun) { return new Singleton(); }
else
{
return null;
}
}
}
单件模式应用程序:
当然你也可以向上面代码添加修饰,如异常管理等。Singleton模式并没有限制只能创建一个对象,也允许你创建固定数量的对象。对于固定数量的对象,你必须处理对象池的对象如何共享这种问题。对象池管理机制下的单件模式样例:
/// <summary>
/// 对象池管理。
/// </summary>
public class PoolManager
{
/// <summary>
/// 对象池中存放的对象实例。
/// </summary>
static class PoolItem
{
public bool inUse = false;
public object item;
public PoolItem(object item) { this.item = item; }
}
ArrayList items = new ArrayList();
public PoolManager(object item)
{
items.Add(new PoolItem(item));
}
public void Add(object item)
{
items.Add(new PoolItem(item));
}
public object Get()
{
for (int i = 0; i < items.Count; i++)
{
PoolItem pitem = (PoolItem)items[i];
if (pitem.inUse == false) { pitem.inUse = true; return pitem.item; }
}
return null;
}
public void Release(object item)
{
for (int i = 0; i < items.Count; i++)
{
PoolItem pitem = (PoolItem)items[i];
if (item == pitem.item) { pitem.inUse = false; return; }
}
}
}
在该对象池管理下的单件模式:
public class PoolSingleton
{
static PoolManager pool = new PoolManager();
public static void AddObject(int number)
{
for (int i = 0; i < number; i++) { pool.Add(new PoolSingleton()); }
}
public static PoolSingleton GetObject() { return (PoolSingleton)pool.Get(); }
public static void ReleaseObject(PoolSingleton o) { pool.Release(o); }
}
这里你只能通过静态方法AddObject创建新的对象,只能通过GetObject方法从对象池中取得单件对象的一个引用。
/// <summary>
/// 使用互斥锁查看对象是否已经创建。这种实现要求:
/// 1、初始化应用程序是请求互斥锁。
/// 2、关闭应用程序时释放互斥锁。
/// </summary>
public static class SingletonApp
{
static Mutex m_Mutex;
public static void Run(Form mainForm)
{
bool first = IsFirstInstance();
if (first)
{
Application.ApplicationExit += OnExit;
Application.Run(mainForm);
}
}
static bool IsFirstInstance()
{
Assembly assembly = Assembly.GetEntryAssembly();
string name = assembly.FullName;
m_Mutex = new Mutex(false, name);
bool owned = false;
owned = m_Mutex.WaitOne(TimeSpan.Zero, false);
return owned;
}
static void OnExit(object sender, EventArgs args)
{
m_Mutex.ReleaseMutex();
m_Mutex.Close();
}
//Other overloaded versions of Run( )
}