singleton設計模式的C#實現(上)
2024-07-21 02:20:04
供稿:網友
singleton設計模式的c#實現
電子科技大學 張申 ([email protected])
關鍵字:singleton 設計模式 同步 c#
1 singleton模式。
singleton(譯為單件或單態)模式是設計模式中比較簡單而常用的模式。
有些時候在整個應用程序中,會要求某個類有且只有一個實例,這個時候可以采用singleton模式進行設計。用singleton模式設計的類不僅能保證在應用中只有一個實例,而且提供了一種非全局變量的方法進行全局訪問,稱為全局訪問點,這樣對于沒有全局變量概念的純面向對象語言來說是非常方便的,比如c#。
本文用一個計數器的例子來描述在c#中如何使用singleton模式:計數的值設計為計數器類的一個私有成員變量,它被4個不同的線程進行讀寫操作,為保證計數的正確性,在整個應用當中必然要求計數器類的實例是唯一的。
2 singleton的實現方式。
首先看看教科書方式的singleton標準實現的兩種方法,以下用的是類c#偽代碼:
方法一:
using system;
namespace cspattern.singleton
{
public class singleton
{
static singleton unisingleton = new singleton();
private singleton() {}
static public singleton instance()
{
return unisingleton;
}
}
}
方法二:
using system;
namespace cspattern.singleton
{
public class singleton
{
static singleton unisingleton;
private singleton() {}
static public singleton instance()
{
if (null == unisingleton)
{
unisingleton = new singleton _lazy();
}
return unisingleton;
}
}
}
singleton模式的實現有兩個技巧:一是使用靜態成員變量保存“全局”的實例,確保了唯一性,使用靜態的成員方法instance() 代替 new關鍵字來獲取該類的實例,達到全局可見的效果。二是將構造方法設置成為private,如果使用new關鍵字創建類的實例,則編譯報錯,以防編程時候筆誤。
上面方法二的初始化方式稱為lazy initialization,是在第一次需要實例的時候才創建類的實例,與方法一中類的實例不管用不用一直都有相比,方法二更加節省系統資源。但是方法二在多線程應用中有時會出現多個實例化的現象。
假設這里有2個線程:主線程和線程1,在創建類的實例的時候可能會遇到一些原因阻塞一段時間(比如網絡速度或者需要等待某些正在使用的資源的釋放),此時的運行情況如下:
主線程首先去調用instance()試圖獲得類的實例,instance()成員方法判斷該類沒有創建唯一實例,于是開始創建實例。由于一些因素,主線程不能馬上創建成功,而需要等待一些時間。此時線程1也去調用instance()試圖獲得該類的實例,因為此時實例還未被主線程成功創建,因此線程1又開始創建新實例。結果是兩個線程分別創建了兩次實例,對于計數器類來說,就會導致計數的值被重置,與singleton的初衷違背。解決這個問題的辦法是同步。
下面看看本文的計數器的例子的實現:
使用方法一:
using system;
using system.threading;
namespace cspattern.singleton
{
public class counter
{
static counter unicounter = new counter(); //存儲唯一的實例。
private int totnum = 0; //存儲計數值。
private counter()
{
thread.sleep(100); //這里假設因為某種因素而耽擱了100毫秒。
//在非lazy initialization 的情況下, 不會影響到計數。.
}
static public counter instance()
{
return unicounter;
}
public void inc() { totnum ++;} //計數加1。
public int getcounter() { return totnum;} //獲得當前計數值。
}
}
以下是調用counter類的客戶程序,在這里我們定義了四個線程同時使用計數器,每個線程使用4次,最后得到的正確結果應該是16:
using system;
using system.io;
using system.threading;
namespace cspattern.singleton.mutilethread
{
public class mutileclient
{
public mutileclient() {}
public void dosomework()
{
counter mycounter = counter.instance(); //方法一
//counter_lazy mycounter = counter_lazy.instance(); //方法二
for (int i = 1; i < 5; i++)
{
mycounter.inc();
console.writeline("線程{0}報告: 當前counter為: {1}", thread.currentthread.name.tostring(), mycounter.getcounter().tostring());
}
}
public void clientmain()
{
thread thread0 = thread.currentthread;
thread0.name = "thread 0";
thread thread1 =new thread(new threadstart(this.dosomework));
thread1.name = "thread 1";
thread thread2 =new thread(new threadstart(this.dosomework));
thread2.name = "thread 2";
thread thread3 =new thread(new threadstart(this.dosomework));
thread3.name = "thread 3";
thread1.start();
thread2.start();
thread3.start();
dosomework(); //線程0也只執行和其他線程相同的工作。
}
}
}
(接下半部分)