Singleton(譯為單件或單態)模式是設計模式中比較簡單而常用的模式
有些時候在整個應用程序中
本文用一個計數器的例子來描述在C#中如何使用Singleton模式
Singleton的實現方式
首先看看教科書方式的Singleton標准實現的兩種方法
方法一
using System;
namespace csPattern
{
public class Singleton
{
static Singleton uniSingleton = new Singleton();
private Singleton() {}
static public Singleton instance()
{
return uniSingleton;
}
}
}
方法二
using System;
namespace csPattern
{
public class Singleton
{
static Singleton uniSingleton;
private Singleton() {}
static public Singleton instance()
{
if (null == uniSingleton)
{
uniSingleton = new Singleton _lazy();
}
return uniSingleton;
}
}
}
Singleton模式的實現有兩個技巧
上面方法二的初始化方式稱為lazy initialization
假設這裡有
主線程首先去調用instance()試圖獲得類的實例
下面看看本文的計數器的例子的實現
使用方法一
using System;
using System
namespace csPattern
{
public class Counter
{
static Counter uniCounter = new Counter(); //存儲唯一的實例
private int totNum =
private Counter()
{
Thread
//在非lazy initialization 的情況下
}
static public Counter instance()
{
return uniCounter;
}
public void Inc() { totNum ++;} //計數加
public int GetCounter() { return totNum;} //獲得當前計數值
}
}
以下是調用Counter類的客戶程序
using System;
using System
using System
namespace csPattern
{
public class MutileClient
{
public MutileClient() {}
public void DoSomeWork()
{
Counter myCounter = Counter
//Counter_lazy myCounter = Counter_lazy
for (int i =
{
myCounter
Console
}
}
public void ClientMain()
{
Thread thread
thread
Thread thread
thread
Thread thread
thread
Thread thread
thread
thread
thread
thread
DoSomeWork(); //線程
}
}
}
以下為Main函數
using System;
namespace csPattern
{
public class RunMain
{
public RunMain() {}
static public void Main(string[] args)
{
MutileThread
myClient
System
}
}
}
執行結果如下
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
線程Thread
由於系統線程調度的不同
方法一中由於實例一開始就被創建
使用方法二
using System;
using System
using System
namespace csPattern
{
public class Counter_lazy
{
static Counter_lazy uniCounter;
private int totNum =
private Counter_lazy()
{
Thread
}
[MethodImpl(MethodImplOptions
static public Counter_lazy instance()
{
if (null == uniCounter)
{
uniCounter = new Counter_lazy();
}
return uniCounter;
}
public void Inc() { totNum ++;}
public int GetCounter() { return totNum;}
}
}
不知道大家有沒有注意到instance()方法上方的[MethodImpl(MethodImplOptions
根據MSDN的提示
using System;
using System
namespace csPattern
{
public class Counter_lazy
{
static Counter_lazy uniCounter;
static object myObject = new object();
private int totNum =
private Counter_lazy()
{
Thread
}
static public Counter_lazy instance()
{
lock(myObject)
{
if (null == uniCounter)
{
uniCounter = new Counter_lazy();
}
return uniCounter;
}
}
public void Inc() { totNum ++;}
public int GetCounter() { return totNum;}
}
}
lock()是對一個對象加互斥鎖
還可以使用Mutex類進行同步
static public Counter_lazy instance()
{
mut
if (null == uniCounter)
{
uniCounter = new Counter_lazy();
}
mut
return uniCounter;
}
注意的是
singleton模式還可以拓展
From:http://tw.wingwit.com/Article/program/net/201311/12545.html