• <ins id="pjuwb"></ins>
    <blockquote id="pjuwb"><pre id="pjuwb"></pre></blockquote>
    <noscript id="pjuwb"></noscript>
          <sup id="pjuwb"><pre id="pjuwb"></pre></sup>
            <dd id="pjuwb"></dd>
            <abbr id="pjuwb"></abbr>

            SoRoMan

            人若無名,便可專心練劍.

              C++博客 :: 首頁 :: 新隨筆 :: 聯(lián)系 :: 聚合  :: 管理 ::
              12 隨筆 :: 1 文章 :: 41 評論 :: 0 Trackbacks

            <轉(zhuǎn)貼-To Me>
            概述

            Singleton模式?

            五種實(shí)現(xiàn)

            1 .簡單實(shí)現(xiàn)

            ?1 public ? sealed ? class ?Singleton
            ?2 {
            ?3 ???? static ?Singleton?instance = null ;
            ?4
            ?5 ????Singleton()
            ?6 ???? {
            ?7 ????}

            ?8
            ?9 ???? public ? static ?Singleton?Instance
            10 ???? {
            11 ???????? get
            12 ???????? {
            13 ???????????? if ?(instance == null )
            14 ???????????? {
            15 ????????????????instance? = ? new ?Singleton();
            16 ????????????}

            17 ???????????? return ?instance;
            18 ????????}

            19 ????}

            20 }

            這種方式的實(shí)現(xiàn)對于線程來說并不是安全的,因?yàn)樵诙嗑€程的環(huán)境下有可能得到Sigleton類的多個實(shí)例。如果同時有兩個線程去判斷(instance == null),并且得到的結(jié)果為真,這時兩個線程都會創(chuàng)建類Sigleton的實(shí)例,這樣就違背了Sigleton模式的原則。實(shí)際上在上述代碼中,有可能在計(jì)算出表達(dá)式的值之前,對象實(shí)例已經(jīng)被創(chuàng)建,但是內(nèi)存模型并不能保證對象實(shí)例在第二個線程創(chuàng)建之前被發(fā)現(xiàn)。

            該實(shí)現(xiàn)方式主要有兩個優(yōu)點(diǎn):

            l???????? 由于實(shí)例是在 Instance屬性方法內(nèi)部創(chuàng)建的,因此類可以使用附加功能(例如,對子類進(jìn)行實(shí)例化),即使它可能引入不想要的依賴性。

            l???????? 直到對象要求產(chǎn)生一個實(shí)例才執(zhí)行實(shí)例化;這種方法稱為“惰性實(shí)例化”。惰性實(shí)例化避免了在應(yīng)用程序啟動時實(shí)例化不必要的 singleton。

            2 .安全的線程

            ?1 public ? sealed ? class ?Singleton
            ?2 {
            ?3 ???? static ?Singleton?instance = null ;
            ?4 ???? static ? readonly ? object ?padlock? = ? new ? object ();
            ?5
            ?6 ????Singleton()
            ?7 ???? {
            ?8 ????}

            ?9
            10 ???? public ? static ?Singleton?Instance
            11 ???? {
            12 ???????? get
            13 ???????? {
            14 ???????????? lock ?(padlock)
            15 ???????????? {
            16 ???????????????? if ?(instance == null )
            17 ???????????????? {
            18 ????????????????????instance? = ? new ?Singleton();
            19 ????????????????}

            20 ???????????????? return ?instance;
            21 ????????????}

            22 ????????}

            23 ????}

            24 }

            25
            26

            這種方式的實(shí)現(xiàn)對于線程來說是安全的。我們首先創(chuàng)建了一個進(jìn)程輔助對象,線程在進(jìn)入時先對輔助對象加鎖然后再檢測對象是否被創(chuàng)建,這樣可以確保只有一個實(shí)例被創(chuàng)建,因?yàn)樵谕粋€時刻加了鎖的那部分程序只有一個線程可以進(jìn)入。這種情況下,對象實(shí)例由最先進(jìn)入的那個線程創(chuàng)建,后來的線程在進(jìn)入時( instence == null )為假,不會再去創(chuàng)建對象實(shí)例了。但是這種實(shí)現(xiàn)方式增加了額外的開銷,損失了性能。

            3 .雙重鎖定

            ?1 public ? sealed ? class ?Singleton
            ?2 {
            ?3 ???? static ?Singleton?instance = null ;
            ?4 ???? static ? readonly ? object ?padlock? = ? new ? object ();
            ?5
            ?6 ????Singleton()
            ?7 ???? {
            ?8 ????}

            ?9
            10 ???? public ? static ?Singleton?Instance
            11 ???? {
            12 ???????? get
            13 ???????? {
            14 ???????????? if ?(instance == null )
            15 ???????????? {
            16 ???????????????? lock ?(padlock)
            17 ???????????????? {
            18 ???????????????????? if ?(instance == null )
            19 ???????????????????? {
            20 ????????????????????????instance? = ? new ?Singleton();
            21 ????????????????????}

            22 ????????????????}

            23 ????????????}

            24 ???????????? return ?instance;
            25 ????????}

            26 ????}

            27 }

            28

            這種實(shí)現(xiàn)方式對多線程來說是安全的,同時線程不是每次都加鎖,只有判斷對象實(shí)例沒有被創(chuàng)建時它才加鎖,有了我們上面第一部分的里面的分析,我們知道,加鎖后還得再進(jìn)行對象是否已被創(chuàng)建的判斷。它 解決了線程并發(fā)問題,同時避免在每個 Instance 屬性方法的調(diào)用中都出現(xiàn)獨(dú)占鎖定。它還允許您將實(shí)例化延遲到第一次訪問對象時發(fā)生。實(shí)際上,應(yīng)用程序很少需要這種類型的實(shí)現(xiàn)。大多數(shù)情況下我們會用靜態(tài)初始化。 這種方式仍然有很多缺點(diǎn):無法實(shí)現(xiàn)延遲初始化。

            4 .靜態(tài)初始化

            ?1 public ? sealed ? class ?Singleton
            ?2 {
            ?3 ???? static ? readonly ?Singleton?instance = new ?Singleton();
            ?4
            ?5 ???? static ?Singleton()
            ?6 ???? {
            ?7 ????}

            ?8
            ?9 ????Singleton()
            10 ???? {
            11 ????}

            12
            13 ???? public ? static ?Singleton?Instance
            14 ???? {
            15 ???????? get
            16 ???????? {
            17 ???????????? return ?instance;
            18 ????????}

            19 ????}

            20 }

            21

            看到上面這段富有戲劇性的代碼,我們可能會產(chǎn)生懷疑,這還是 Sigleton 模式嗎? 在此實(shí)現(xiàn)中,將在第一次引用類的任何成員時創(chuàng)建實(shí)例。公共語言運(yùn)行庫負(fù)責(zé)處理變量初始化。該類標(biāo)記為 sealed 以阻止發(fā)生派生,而派生可能會增加實(shí)例。此外,變量標(biāo)記為 readonly,這意味著只能在靜態(tài)初始化期間(此處顯示的示例)或在類構(gòu)造函數(shù)中分配變量。

            該實(shí)現(xiàn)與前面的示例類似,不同之處在于它依賴公共語言運(yùn)行庫來初始化變量。它仍然可以用來解決 Singleton模式試圖解決的兩個基本問題:全局訪問和實(shí)例化控制。公共靜態(tài)屬性為訪問實(shí)例提供了一個全局訪問點(diǎn)。此外,由于構(gòu)造函數(shù)是私有的,因此不能在類本身以外實(shí)例化 Singleton 類;因此,變量引用的是可以在系統(tǒng)中存在的唯一的實(shí)例。

            由于 Singleton 實(shí)例被私有靜態(tài)成員變量引用,因此在類首次被對 Instance屬性的調(diào)用所引用之前,不會發(fā)生實(shí)例化。

            這種方法唯一的潛在缺點(diǎn)是,您對實(shí)例化機(jī)制的控制權(quán)較少。在Design Patterns形式中,您能夠在實(shí)例化之前使用非默認(rèn)的構(gòu)造函數(shù)或執(zhí)行其他任務(wù)。由于在此解決方案中由 .NET Framework 負(fù)責(zé)執(zhí)行初始化,因此您沒有這些選項(xiàng)。在大多數(shù)情況下,靜態(tài)初始化是在 .NET 中實(shí)現(xiàn) Singleton的首選方法。

            5 .延遲初始化

            ?1 public ? sealed ? class ?Singleton
            ?2 {
            ?3 ????Singleton()
            ?4 ???? {
            ?5 ????}

            ?6
            ?7 ???? public ? static ?Singleton?Instance
            ?8 ???? {
            ?9 ???????? get
            10 ???????? {
            11 ???????????? return ?Nested.instance;
            12 ????????}

            13 ????}

            14 ????
            15 ???? class ?Nested
            16 ???? {
            17 ???????? static ?Nested()
            18 ???????? {
            19 ????????}

            20
            21 ???????? internal ? static ? readonly ?Singleton?instance? = ? new ?Singleton();
            22 ????}

            23 }

            24

            這里,初始化工作有Nested類的一個靜態(tài)成員來完成,這樣就實(shí)現(xiàn)了延遲初始化,并具有很多的優(yōu)勢,是值得推薦的一種實(shí)

            現(xiàn)方式。

            實(shí)現(xiàn)要點(diǎn)

            l??????? Sigleton模式是限制而不是改進(jìn)類的創(chuàng)建。

            l???????? Sigleton類中的實(shí)例構(gòu)造器可以設(shè)置為Protected以允許子類派生。

            l???????? Sigleton模式一般不要支持Icloneable接口,因?yàn)檫@可能導(dǎo)致多個對象實(shí)例,與Sigleton模式的初衷違背。

            l???????? Sigleton模式一般不要支持序列化,這也有可能導(dǎo)致多個對象實(shí)例,這也與Sigleton模式的初衷違背。

            l???????? Sigleton只考慮了對象創(chuàng)建的管理,沒有考慮到銷毀的管理,就支持垃圾回收的平臺和對象的開銷來講,我們一般沒必要對其銷毀進(jìn)行特殊的管理。

            l???????? 理解和擴(kuò)展Sigleton模式的核心是“如何控制用戶使用new對一個類的構(gòu)造器的任意調(diào)用”。

            l???????? 可以很簡單的修改一個 Sigleton ,使它有少數(shù)幾個實(shí)例,這樣做是允許的而且是有意義的 。

            優(yōu)點(diǎn)

            l???????? 實(shí)例控制: Singleton 會阻止其他對象實(shí)例化其自己的 Singleton對象的副本,從而確保所有對象都訪問唯一實(shí)例

            l???????? 靈活性:因?yàn)轭惪刂屏藢?shí)例化過程,所以類可以更加靈活修改實(shí)例化過程

            缺點(diǎn)

            l???????? 開銷:雖然數(shù)量很少, 但如果每次對象請求引用時都要檢查是否存在類的實(shí)例,將仍然需要一些開銷。可以通過使用靜態(tài)初始化解決此問題,上面的五種實(shí)現(xiàn)方式中已經(jīng)說過了。

            l????????? 可能的開發(fā)混淆: 使用 singleton 對象(尤其在類庫中定義的對象)時,開發(fā)人員必須記住自己不能使用 new 關(guān)鍵字實(shí)例化對象。因?yàn)榭赡軣o法訪問庫源代碼,因此應(yīng)用程序開發(fā)人員可能會意外發(fā)現(xiàn)自己無法直接實(shí)例化此類。

            l???????? 對象的生存期: Singleton 不能解決刪除單個對象的問題。在提供內(nèi)存管理的語言中(例如基于 .NET Framework 的語言),只有 Singleton類能夠?qū)е聦?shí)例被取消分配,因?yàn)樗瑢υ搶?shí)例的私有引用。在某些語言中(如 C++),其他類可以刪除
            對象實(shí)例,但這樣會導(dǎo)致 Singleton類中出現(xiàn)懸浮引用。

            適用性

            l???????? 當(dāng)類只能有一個實(shí)例而且客戶可以從一個眾所周知的訪問點(diǎn)訪問它時。

            l???????? 當(dāng)這個唯一實(shí)例應(yīng)該是通過子類化可擴(kuò)展的,并且客戶應(yīng)該無需更改代碼就能使用一個擴(kuò)展的實(shí)例時。

            應(yīng)用場景

            l???????? 每臺計(jì)算機(jī)可以有若干個打印機(jī),但只能有一個 Printer Spooler ,避免兩個打印作業(yè)同時輸出到打印機(jī)。
            (摘自呂震宇的
            C# 設(shè)計(jì)模式(7 )-Singleton Pattern

            l???????? PC 機(jī)中可能有幾個串口,但只能有一個 COM1 口的實(shí)例。

            l???????? 系統(tǒng)中只能有一個窗口管理器。

            l???????? .NET Remoting 中服務(wù)器激活對象中的 Sigleton 對象,確保所有的客戶程序的請求都只有一個實(shí)例來處理。

            完整示例

            這是一個簡單的計(jì)數(shù)器例子,四個線程同時進(jìn)行計(jì)數(shù)。

            ?1 using ?System;
            ?2 using ?System.Threading;
            ?3
            ?4 namespace ?SigletonPattern.SigletonCounter
            ?5 {
            ?6 ???? /**/ /// ? <summary>
            ?7 ???? /// ?功能:簡單計(jì)數(shù)器的單件模式
            ?8 ???? /// ?編寫:Terrylee
            ?9 ???? /// ?日期:2005年12月06日
            10 ???? /// ? </summary>

            11 ???? public ? class ?CountSigleton
            12 ???? {
            13 ???????? /**/ /// 存儲唯一的實(shí)例
            14 ???????? static ?CountSigleton?uniCounter? = ? new ?CountSigleton();??
            15 ???
            16 ???????? /**/ /// 存儲計(jì)數(shù)值
            17 ???????? private ? int ?totNum? = ? 0 ;??
            18 ???
            19 ???????? private ?CountSigleton()?
            20 ???
            21 ???????? {?
            22 ???????????? /**/ /// 線程延遲2000毫秒
            23 ????????????Thread.Sleep( 2000 );
            24 ????????}
            ?
            25 ???
            26 ???????? static ? public ?CountSigleton?Instance()?
            27 ???
            28 ???????? {?
            29 ???
            30 ???????????? return ?uniCounter;?
            31 ???
            32 ????????}
            ?
            33 ????????
            34 ???????? /**/ /// 計(jì)數(shù)加1
            35 ???????? public ? void ?Add()
            36 ???????? {?
            37 ????????????totNum? ++ ;
            38 ????????}
            ??
            39 ????????
            40 ???????? /**/ /// 獲得當(dāng)前計(jì)數(shù)值
            41 ???????? public ? int ?GetCounter()
            42 ???????? {?
            43 ???????????? return ?totNum;
            44 ????????}
            ?
            45
            46 ????}

            47 }

            48

            ?1 using ?System;
            ?2 using ?System.Threading;
            ?3 using ?System.Text;
            ?4
            ?5 namespace ?SigletonPattern.SigletonCounter
            ?6 {
            ?7 ???? /**/ /// ? <summary>
            ?8 ???? /// ?功能:創(chuàng)建一個多線程計(jì)數(shù)的類
            ?9 ???? /// ?編寫:Terrylee
            10 ???? /// ?日期:2005年12月06日
            11 ???? /// ? </summary>

            12 ???? public ? class ?CountMutilThread
            13 ???? {
            14 ???????? public ?CountMutilThread()
            15 ???????? {
            16 ????????????
            17 ????????}

            18
            19 ???????? /**/ /// ? <summary>
            20 ???????? /// ?線程工作
            21 ???????? /// ? </summary>

            22 ???????? public ? static ? void ?DoSomeWork()
            23 ???????? {
            24 ???????????? /**/ /// 構(gòu)造顯示字符串
            25 ???????????? string ?results? = ? "" ;
            26
            27 ???????????? /**/ /// 創(chuàng)建一個Sigleton實(shí)例
            28 ???CountSigleton?MyCounter? = ?CountSigleton.Instance();
            29
            30 ???????????? /**/ /// 循環(huán)調(diào)用四次
            31 ???????????? for ( int ?i = 1 ;i < 5 ;i ++ )
            32 ???????????? {
            33 ??????? /**/ /// 開始計(jì)數(shù)
            34 ????????????????MyCounter.Add();
            35 ????????????????
            36 ????????????????results? += " 線程 " ;
            37 ????????????????results? += ?i.ToString()? + ? " ——〉 " ;
            38 ????????????????results? += ? " 當(dāng)前的計(jì)數(shù): " ;
            39 ????????????????results? += ?MyCounter.GetCounter().ToString();
            40 ????????????????results? += ? " \n " ;
            41
            42 ????????????????Console.WriteLine(results);
            43 ????????????????
            44 ???????????????? /**/ /// 清空顯示字符串
            45 ?????????results? = ? "" ;
            46 ????????????}

            47 ????????}

            48
            49 ???????? public ? void ?StartMain()
            50 ???????? {
            51
            52 ????????????Thread?thread0? = ?Thread.CurrentThread;?
            53 ???
            54 ????????????thread0.Name? = ? " Thread?0 " ;?
            55 ???
            56 ????????????Thread?thread1? = new ?Thread( new ?ThreadStart(DoSomeWork));?
            57 ???
            58 ????????????thread1.Name? = ? " Thread?1 " ;?
            59 ???
            60 ????????????Thread?thread2? = new ?Thread( new ?ThreadStart(DoSomeWork));?
            61 ???
            62 ????????????thread2.Name? = ? " Thread?2 " ;?
            63 ???
            64 ????????????Thread?thread3? = new ?Thread( new ?ThreadStart(DoSomeWork));?
            65 ???
            66 ????????????thread3.Name? = ? " Thread?3 " ;?
            67 ???
            68 ????????????thread1.Start();?
            69 ???
            70 ????????????thread2.Start();?
            71 ???
            72 ????????????thread3.Start();?
            73 ????????????
            74 ???????????? /**/ /// 線程0也只執(zhí)行和其他線程相同的工作
            75 ????????????DoSomeWork();?
            76 ????????}

            77 ????}

            78 }

            79

            ?1 using ?System;
            ?2 using ?System.Text;
            ?3 using ?System.Threading;
            ?4
            ?5 namespace ?SigletonPattern.SigletonCounter
            ?6 {
            ?7 ???? /**/ /// ? <summary>
            ?8 ???? /// ?功能:實(shí)現(xiàn)多線程計(jì)數(shù)器的客戶端
            ?9 ???? /// ?編寫:Terrylee
            10 ???? /// ?日期:2005年12月06日
            11 ???? /// ? </summary>

            12 ???? public ? class ?CountClient
            13 ???? {
            14 ???????? public ? static ? void ?Main( string []?args)
            15 ???????? {
            16 ???????CountMutilThread?cmt? = ? new ?CountMutilThread();
            17
            18 ????????????cmt.StartMain();
            19
            20 ????????????Console.ReadLine();
            21 ????????}

            22 ????}

            23 }

            24

            總結(jié)

            Sigleton 設(shè)計(jì)模式是一個非常有用的機(jī)制,可用于在面向?qū)ο蟮膽?yīng)用程序中提供單個訪問點(diǎn)。文中通過五種實(shí)現(xiàn)方式的比較和一個完整的示例,完成了對 Sigleton 模式的一個總結(jié)和探索。用一句廣告詞來概括 Sigleton 模式就是“簡約而不簡單”。

            源碼下載:/Files/Terrylee/SigletonPattern.rar


            ?

            一、?單例(Singleton)模式

            單例模式的特點(diǎn):

            • 單例類只能有一個實(shí)例。
            • 單例類必須自己創(chuàng)建自己的唯一實(shí)例。
            • 單例類必須給所有其它對象提供這一實(shí)例。

            單例模式應(yīng)用:

            • 每臺計(jì)算機(jī)可以有若干個打印機(jī),但只能有一個Printer Spooler,避免兩個打印作業(yè)同時輸出到打印機(jī)。
            • 一個具有自動編號主鍵的表可以有多個用戶同時使用,但數(shù)據(jù)庫中只能有一個地方分配下一個主鍵編號。否則會出現(xiàn)主鍵重復(fù)。


            二、?Singleton模式的結(jié)構(gòu):

            Singleton模式包含的角色只有一個,就是Singleton。Singleton擁有一個私有構(gòu)造函數(shù),確保用戶無法通過new直接實(shí)例它。除此之外,該模式中包含一個靜態(tài)私有成員變量instance與靜態(tài)公有方法Instance()。Instance方法負(fù)責(zé)檢驗(yàn)并實(shí)例化自己,然后存儲在靜態(tài)成員變量中,以確保只有一個實(shí)例被創(chuàng)建。(關(guān)于線程問題以及C#所特有的Singleton將在后面詳細(xì)論述)。


            三、?程序舉例:

            該程序演示了Singleton的結(jié)構(gòu),本身不具有任何實(shí)際價(jià)值。

            // ?Singleton?pattern?--?Structural?example??
            using ?System;

            // ?"Singleton"
            class ?Singleton
            {
            ??
            // ?Fields
            ?? private ? static ?Singleton?instance;

            ??
            // ?Constructor
            ?? protected ?Singleton()? {}

            ??
            // ?Methods
            ?? public ? static ?Singleton?Instance()
            ??
            {
            ????
            // ?Uses?"Lazy?initialization"
            ???? if (?instance? == ? null ?)
            ??????instance?
            = ? new ?Singleton();

            ????
            return ?instance;
            ??}

            }


            /// ? <summary>
            /// ?Client?test
            /// ? </summary>

            public ? class ?Client
            {
            ??
            public ? static ? void ?Main()
            ??
            {
            ????
            // ?Constructor?is?protected?--?cannot?use?new
            ????Singleton?s1? = ?Singleton.Instance();
            ????Singleton?s2?
            = ?Singleton.Instance();

            ????
            if (?s1? == ?s2?)
            ??????Console.WriteLine(?
            " The?same?instance " ?);
            ??}

            }



            四、?在什么情形下使用單例模式:

            使用Singleton模式有一個必要條件:在一個系統(tǒng)要求一個類只有一個實(shí)例時才應(yīng)當(dāng)使用單例模式。反過來,如果一個類可以有幾個實(shí)例共存,就不要使用單例模式。

            注意:

            不要使用單例模式存取全局變量。這違背了單例模式的用意,最好放到對應(yīng)類的靜態(tài)成員中。

            不要將數(shù)據(jù)庫連接做成單例,因?yàn)橐粋€系統(tǒng)可能會與數(shù)據(jù)庫有多個連接,并且在有連接池的情況下,應(yīng)當(dāng)盡可能及時釋放連接。Singleton模式由于使用靜態(tài)成員存儲類實(shí)例,所以可能會造成資源無法及時釋放,帶來問題。


            五、?Singleton模式在實(shí)際系統(tǒng)中的實(shí)現(xiàn)

            下面這段Singleton代碼演示了負(fù)載均衡對象。在負(fù)載均衡模型中,有多臺服務(wù)器可提供服務(wù),任務(wù)分配器隨機(jī)挑選一臺服務(wù)器提供服務(wù),以確保任務(wù)均衡(實(shí)際情況比這個復(fù)雜的多)。這里,任務(wù)分配實(shí)例只能有一個,負(fù)責(zé)挑選服務(wù)器并分配任務(wù)。

            // ?Singleton?pattern?--?Real?World?example??

            using ?System;
            using ?System.Collections;
            using ?System.Threading;

            // ?"Singleton"
            class ?LoadBalancer
            {
            ??
            // ?Fields
            ?? private ? static ?LoadBalancer?balancer;
            ??
            private ?ArrayList?servers? = ? new ?ArrayList();
            ??
            private ?Random?random? = ? new ?Random();

            ??
            // ?Constructors?(protected)
            ?? protected ?LoadBalancer()
            ??
            {
            ????
            // ?List?of?available?servers
            ????servers.Add(? " ServerI " ?);
            ????servers.Add(?
            " ServerII " ?);
            ????servers.Add(?
            " ServerIII " ?);
            ????servers.Add(?
            " ServerIV " ?);
            ????servers.Add(?
            " ServerV " ?);
            ??}


            ??
            // ?Methods
            ?? public ? static ?LoadBalancer?GetLoadBalancer()
            ??
            {
            ????
            // ?Support?multithreaded?applications?through
            ????
            // ?"Double?checked?locking"?pattern?which?avoids
            ????
            // ?locking?every?time?the?method?is?invoked
            ???? if (?balancer? == ? null ?)
            ????
            {
            ??????
            // ?Only?one?thread?can?obtain?a?mutex
            ??????Mutex?mutex? = ? new ?Mutex();
            ??????mutex.WaitOne();

            ??????
            if (?balancer? == ? null ?)
            ????????balancer?
            = ? new ?LoadBalancer();

            ??????mutex.Close();
            ????}

            ????
            return ?balancer;
            ??}


            ??
            // ?Properties
            ?? public ? string ?Server
            ??
            {
            ????
            get
            ????
            {
            ??????
            // ?Simple,?but?effective?random?load?balancer
            ?????? int ?r? = ?random.Next(?servers.Count?);
            ??????
            return ?servers[?r?].ToString();
            ????}

            ??}

            }


            /// ? <summary>
            /// ?SingletonApp?test
            /// ? </summary>
            ///

            public ? class ?SingletonApp
            {
            ??
            public ? static ? void ?Main(? string []?args?)
            ??
            {
            ????LoadBalancer?b1?
            = ?LoadBalancer.GetLoadBalancer();
            ????LoadBalancer?b2?
            = ?LoadBalancer.GetLoadBalancer();
            ????LoadBalancer?b3?
            = ?LoadBalancer.GetLoadBalancer();
            ????LoadBalancer?b4?
            = ?LoadBalancer.GetLoadBalancer();

            ????
            // ?Same?instance?
            ???? if (?(b1? == ?b2)? && ?(b2? == ?b3)? && ?(b3? == ?b4)?)
            ??????Console.WriteLine(?
            " Same?instance " ?);

            ????
            // ?Do?the?load?balancing
            ????Console.WriteLine(?b1.Server?);
            ????Console.WriteLine(?b2.Server?);
            ????Console.WriteLine(?b3.Server?);
            ????Console.WriteLine(?b4.Server?);
            ??}

            }



            六、?C#中的Singleton模式

            C#的獨(dú)特語言特性決定了C#擁有實(shí)現(xiàn)Singleton模式的獨(dú)特方法。這里不再贅述原因,給出幾個結(jié)果:

            方法一:

            下面是利用.NET Framework平臺優(yōu)勢實(shí)現(xiàn)Singleton模式的代碼:

            sealed ? class ?Singleton
            {
            ???
            private ?Singleton();
            ???
            public ? static ? readonly ?Singleton?Instance = new ?Singleton();
            }

            這使得代碼減少了許多,同時也解決了線程問題帶來的性能上損失。那么它又是怎樣工作的呢?

            注意到,Singleton類被聲明為sealed,以此保證它自己不會被繼承,其次沒有了Instance的方法,將原來_instance成員變量變成public readonly,并在聲明時被初始化。通過這些改變,我們確實(shí)得到了Singleton的模式,原因是在JIT的處理過程中,如果類中的static屬性被任何方法使用時,.NET Framework將對這個屬性進(jìn)行初始化,于是在初始化Instance屬性的同時Singleton類實(shí)例得以創(chuàng)建和裝載。而私有的構(gòu)造函數(shù)和readonly(只讀)保證了Singleton不會被再次實(shí)例化,這正是Singleton設(shè)計(jì)模式的意圖。
            (摘自:http://www.cnblogs.com/huqingyu/archive/2004/07/09/22721.aspx

            不過這也帶來了一些問題,比如無法繼承,實(shí)例在程序一運(yùn)行就被初始化,無法實(shí)現(xiàn)延遲初始化等。

            詳細(xì)情況可以參考微軟MSDN文章:《Exploring the Singleton Design Pattern》

            方法二:

            既然方法一存在問題,我們還有其它辦法。

            public ? sealed ? class ?Singleton
            {
            ??Singleton()
            ??
            {
            ??}


            ??
            public ? static ?Singleton?GetInstance()
            ??
            {
            ????
            return ?Nested.instance;
            ??}

            ????
            ??
            class ?Nested
            ??
            {
            ????
            // ?Explicit?static?constructor?to?tell?C#?compiler
            ????
            // ?not?to?mark?type?as?beforefieldinit
            ???? static ?Nested()
            ????
            {
            ????}


            ????
            internal ? static ? readonly ?Singleton?instance? = ? new ?Singleton();
            ??}

            }

            這實(shí)現(xiàn)了延遲初始化,并具有很多優(yōu)勢,當(dāng)然也存在一些缺點(diǎn)。詳細(xì)內(nèi)容請?jiān)L問:《Implementing the Singleton Pattern in C#》。文章包含五種Singleton實(shí)現(xiàn),就模式、線程、效率、延遲初始化等很多方面進(jìn)行了詳細(xì)論述。

            posted on 2006-07-16 23:12 SoRoMan 閱讀(1552) 評論(3)  編輯 收藏 引用

            評論

            # 哇~小雞好厲害^_^崇拜ing~re: Design Pattern之Singleton模式 2006-07-17 10:25 Catherine
            小雞辛苦了~
            俺好好看!  回復(fù)  更多評論
              

            # 小雞面試成功~~re: Design Pattern之Singleton模式 2006-07-19 10:04 Catherine
            今天小雞去9you面試~
            預(yù)祝成功^_^  回復(fù)  更多評論
              

            # re: Design Pattern之Singleton模式 2007-12-30 08:52 sdgsdg
            http://eros-amatoriale-gratuito.gradis-tun.info
            http://video-xxx-89-com.sculaccia-tun.info
            http://maschio-nudo-coito-anale.sculaccia-tun.info
            http://cerco-donna-sesso-pulito.gradis-tun.info
            http://gay-hairy-men.gradis-tun.info
            http://farm-beast-porno-zoo-gratis-clip.sculaccia-tun.info
            http://incontro-sesso-tre.fatte-tun.info
            http://matura-daily-gallery.gradis-tun.info
            http://trans-riceve-a-roma.sculaccia-tun.info
            http://foto-sesso-anale-cazzo-grosso-nero.gradis-tun.info
            http://filmati-maialone-freeware.gradis-tun.info
            http://grande-obese-figa.fatte-tun.info
            http://foto-fatish.fatte-tun.info
            http://super-sexi-hard-moovie.sculaccia-tun.info
            http://anteprime-gratis-donna-porca.sculaccia-tun.info
            http://forum-sito-porno-gratis.gradis-tun.info
            http://posizione-deel-sesso.sculaccia-tun.info
            http://sesso-rio-de-janeiro.fatte-tun.info
            http://hot-girl-xxx.fatte-tun.info
            http://veb-cam-gÄarl.gradis-tun.info
            http://anteprime-gratis-film-porno.sculaccia-tun.info
            http://sesso-orale-lesbo.gradis-tun.info
            http://foto-video-porno-asiatica-gratis.sculaccia-tun.info
            http://figa-vecchia-casalinga-gratis.fatte-tun.info
            http://marco-passera-basket.gradis-tun.info
            http://giovane-ragazza-fanno-sesso.sculaccia-tun.info
            http://sesso-al-telefono-solo-ascolto.sculaccia-tun.info  回復(fù)  更多評論
              


            只有注冊用戶登錄后才能發(fā)表評論。
            網(wǎng)站導(dǎo)航: 博客園   IT新聞   BlogJava   博問   Chat2DB   管理


            婷婷五月深深久久精品| 亚洲AV日韩AV永久无码久久| 久久精品人人做人人妻人人玩| 久久国产美女免费观看精品| 久久综合中文字幕| jizzjizz国产精品久久| 久久精品aⅴ无码中文字字幕重口 久久精品a亚洲国产v高清不卡 | 蜜臀久久99精品久久久久久小说| 人妻中文久久久久| 偷偷做久久久久网站| 伊人久久亚洲综合影院| 久久这里只有精品首页| 亚洲中文精品久久久久久不卡| 亚洲人成网亚洲欧洲无码久久| 东方aⅴ免费观看久久av| 色诱久久久久综合网ywww| 999久久久免费精品国产| 中文字幕亚洲综合久久2| 久久se精品一区二区影院| 欧美久久久久久精选9999| 午夜精品久久久内射近拍高清 | 人妻无码αv中文字幕久久 | 26uuu久久五月天| 久久人人爽人人澡人人高潮AV| 久久综合亚洲鲁鲁五月天| 国产精品久久久久…| 久久精品夜色噜噜亚洲A∨| 国产精品美女久久福利网站| 精品久久久噜噜噜久久久 | 99久久精品免费观看国产| 亚洲欧美国产精品专区久久| 亚洲精品乱码久久久久久自慰 | 久久强奷乱码老熟女网站| 模特私拍国产精品久久| 国产精品久久久久国产A级| 久久乐国产精品亚洲综合| 精品国产VA久久久久久久冰 | 欧美黑人激情性久久| 久久伊人色| 国产午夜福利精品久久| 日韩精品久久无码中文字幕|