單件模式

SINGLETON(單件)

       幾乎所有面向對象的程序中,總有一些類的對象需要是唯一的,例如,通過數據庫句柄到數據庫的連接是獨佔的。您希望在應用程序中共享數據庫句柄,因爲在保持連接打開或關閉時,它是一種開銷。再如大家最經常用的IM,如QQ,在同一臺電腦,一個帳號只能有唯一的登錄。

1. 問題

怎樣確保一個特殊類的實例是獨一無二的(它是這個類的唯一實例),並且這個實例易於被訪問呢?


2. 解決方案

1)全局變量:一個全局變量使得一個對象可以被訪問,但它不能防止你實例化多個對象。因爲你的任何代碼都能修改全局變量,這將不可避免的引起更多調試的意外。換句話說,全局變量的狀態總是會出現一些問題的。

2)類構造函數私有和類自身的靜態方法:讓類自身負責保存它的唯一實例(靜態變量)。這個類可以保證沒有其他實例可以被創建(通過截取創建新對象的請求) ,並且它可以提供一個訪問該實例的方法(靜態方法)。這就是Singleton模式。換句話說,創建實例的事情由我自己來做,不允許別人隨便創建。


3. 適用性
在下面的情況下可以使用單件模式
1)當類只能有一個實例而且客戶可以從一個衆所周知的訪問點訪問它時。

2)當這個唯一實例應該是通過子類化可擴展的,並且客戶應該無需更改代碼就能使用一個擴展的實例時。


4. 實現:

UML結構:

public sealed class Singleton 
{  
    private static $_instance = null;//靜態成員保存唯一實例  
    /** 
     * 私有無參構造函數,保證不能被外部訪問 
     */  
    private Singleton() {}   
    /** 
     * 靜態屬性將創建這個實例的操作並保證只有一個實例被創建,也可以使用靜態方法。
     * @return unknown 
     */  
    public static Singleton Instance
    {  
        get
        {
            if (instance == null)
            {
                instance = new Singleton();
            }
            return instance;
        }
    } //使用靜態方法可以創建帶參數的實例 
}  

幾個要點:

(1) 構造函數可以設置爲protected,這樣允許子類派生做擴展。

(2)一般不支持ICloneable接口,也不支持序列化操作。Clone和序列化反序列化會導致多個對象實例。

(3)模式沒有考慮對象銷燬管理。

(4)不改造不應用於多線程。同步問題可能導致多個對象實例。見6.


5. 效果

   Singleton模式有許多優點
1)  對唯一實例的受控訪問, 因爲Singleton類封裝它的唯一實例,所以它可以嚴格的控制客戶怎樣以及何時訪問它。
2)  縮小名空間,Singleton模式是對全局變量的一種改進。它避免了那些存儲唯一實例的全局變量污染名空間。
3)  允許對操作和表示的精化Singleton類可以有子類,而且用這個擴展類的實例來配置一個應用是很容易的。你可以用你所需要的類的實例在運行時刻配置應用。
4)  允許可變數目的實例 這個模式使得你易於改變你的想法,並允許Singleton類的多個實例。此外,你可以用相同的方法來控制應用所使用的實例的數目。只有允許訪問 Singleton實例的操作需要改變。


6 .多線程單件模式

public sealed class Singleton 
{  
    private static object lockHelper = new object();
    private static volatile $_instance = null;//靜態成員保存唯一實例  
    /** 
     * 私有構造函數,保證不能被外部訪問 
     */  
    private Singleton() {}   
    /** 
     * 靜態方法將創建這個實例的操作並保證只有一個實例被創建 
     * @return unknown 
     */  
    public static Singleton Instance
    {  
        get
        {
            if (instance == null)
            {
                lock(lockHelper)
                {
                    if (instance == null)//double check機制的使用,往後看
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }  
}  

7.另一種實現

public sealed class Singleton
{
    public static readonly Singleton instance = new Singleton();

    private Singleton()
    {}
}

等價於:

public sealed class Singleton
{
    public static readonly Singleton instance;
    //.NET運行庫在第一次調用類成員之前執行靜態構造函數,只執行一次,
    //在使用Singleton的實例之前,.NET保證先調用靜態構造函數,
    //將實例初始化放到靜態構造函數中,保證了實例使用時已經被建,
    //也保證了不使用Singleton實例的話,實例不會被創建,
    //同時,靜態構造函數只能由一個線程執行。
    //缺陷:不能帶參數,不過能用屬性等辦法實現。
    static Singleton()
    {
        instance = new Singleton();
    }

    private Singleton()
    {}
}

8.擴展

(1)創建固定數量n個實例,例如對象池的實現

單件模式並不是說一個類只能只有一個實例。假設我們使用在一個web 請求或者進程裏面。一個用戶id對應的某個類只能有唯一的實例。在下面的例子中,我們的User類,可以有多個實例,每個實例對應一個uid. 實例列表註冊到靜態變量$_instance並和uid關聯起來。最簡單的例子是我們前面提到的QQ,在同一臺電腦,可以使用多帳號登錄, 但一個帳號只能有唯一的登錄.


9.應用

在zend framework中的Zend_Controller_Front前端控制器,就是採用單價模式來設計的:

Zend_Controller_Front是Zend_Controller_Controller體系的組織者,它是FrontController設計模式的實現。

Zend_Controller_Front處理服務器接受的所有請求,並最後負責將請求分配給ActionController(Zend_Controller_Action) 


    $frontController = Zend_Controller_Front::getInstance();  
    $frontController->addModuleDirectory( “參數”);  
    $frontController->dispatch();  


--------------------------------------------------------------------------------------------------------------


另一篇博文,前面幾種和上文大同小異,最後一種實現起來不太一樣~


Implementing the Singleton Pattern in C#


The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.

All these implementations share four common characteristics, however:

A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
A static variable which holds a reference to the single created instance, if any.
A public static means of getting the reference to the single created instance, creating one if necessary.
Note that all of these implementations also use a public static method GetInstance as the means of accessing the instance. In all cases, the method could easily be converted to a property with only an accessor, with no impact on thread-safety or performance.

First version - not thread-safe

public sealed class Singleton
{ 
      static Singleton instance=null; 
      Singleton() 
      { 
      }
      public static Singleton GetInstance() 
      {
            if (instance==null) 
            instance = new Singleton(); 
            return instance; 
      }
 } 

As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety

public sealed class Singleton
{ 
      static Singleton instance=null; 
      static readonly object padlock = new object(); 
      Singleton() 
      { 
      }
       public static Singleton GetInstance() 
      { 
            lock (padlock) 
            { 
                  if (instance==null) 
                  instance = new Singleton(); 
                  return instance;
             } 
      }
}

This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whether or not the instance has been created before creating the instance. This takes care of the memory barrier issue (as locking makes sure that all reads occur logically after the lock acquire, and unlocking makes sure that all writes occur logically before the lock release) and ensures that only one thread will create an instance (as only one thread can be in that part of the code at a time - by the time the second thread enters it,the first thread will have created the instance, so the expression will evaluate to false). Unfortunately, performance suffers as a lock is acquired every time the instance is requested.

Note that instead of locking on typeof(Singleton) as some versions of this implementation do, I lock on the value of a static variable which is private to the class. Locking on objects which other classes can access and lock on (such as the type) risks performance issues and even deadlocks. This is a general style preference of mine - wherever possible, only lock on objects specifically created for the purpose of locking, or which document that they are to be locked on for specific purposes (e.g. for waiting/pulsing a queue). Usually such objects should be private to the class they are used in. This helps to make writing thread-safe applications significantly easier.

Third version - attempted thread-safety using double-check locking

public sealed class Singleton
{ 
      static Singleton instance=null; 
      static readonly object padlock = new object(); 
      Singleton() 
      { 
      } 
      public static Singleton GetInstance() 
      { 
            if (instance==null) 
            { 
                  lock (padlock) 
                  {
                        if (instance==null) 
                        instance = new Singleton(); 
                  } 
            } 
            return instance;
      }
} 

This implementation attempts to be thread-safe without the necessity of taking out a lock every time. Unfortunately, there are four downsides to the pattern:

It doesn't work in Java. This may seem an odd thing to comment on, but it's worth knowing if you ever need the singleton pattern in Java, and C# programmers may well also be Java programmers. The Java memory model doesn't ensure that the constructor completes before the reference to the new object is assigned to instance. The Java memory model is going through a reworking for version 1.5, but double-check locking is anticipated to still be broken after this.
It almost certainly doesn't work in .NET either. Claims have been made that it does, but without any convincing evidence. Various people who are rather more trustworthy, however, such as Chris Brumme, have given convincing reasons why it doesn't. Given the other disadvantages, why take the risk? I believe it can be fixed by making the instance variable volatile, but that slows the pattern down more. (Of course, correct but slow is better than incorrect but broken, but when speed was one of the reasons for using this pattern in the first place, it looks even less attractive.) It can also be fixed using explicit memory barriers, but experts seem to find it hard to agree on just which memory barriers are required. I don't know about you, but when experts disagree about whether or not something should work, I try to avoid it entirely.
It's easy to get wrong. The pattern needs to be pretty much exactly as above - any significant changes are likely to impact either performance or correctness.
It still doesn't perform as well as the later implementations.
 
Fourth version - not quite as lazy, but thread-safe without using locks

public sealed class Singleton
{ 
      static readonly Singleton instance=new Singleton(); 
      // Explicit static constructor to tell C# compiler
      // not to mark type as beforefieldinit 
      static Singleton() 
      { 
      } 
      Singleton() 
      { 
      } 
      public static Singleton GetInstance() 
      { 
            return instance; 
      }
}

As you can see, this is really is extremely simple - but why is it thread-safe and how lazy is it? Well, static constructors in C# are specified to execute only when an instance of the class is created or a static member is referenced, and to execute only once per AppDomain. Given that this check for the type being newly constructed needs to be executed whatever else happens, it will be faster than adding extra checking as in the previous examples. There are a couple of wrinkles, however:

It's not as lazy as the other implementations. In particular, if you have static members other than GetInstance, the first reference to those members will involve creating the instance. This is corrected in the next implementation.
There are complications if one static constructor invokes another which invokes the first again. Look in the .NET specifications (currently section 9.5.3 of partition II) for more details about the exact nature of type initializers - they're unlikely to bite you, but it's worth being aware of the consequences of static constructors which refer to each other in a cycle.
The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called beforefieldinit. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as beforefieldinit. I now have a discussion page with more details about this issue. Also note that it affects performance, as discussed near the bottom of this article.

One shortcut you can take with this implementation (and only this one) is to just make instance a public static readonly variable, and get rid of the method entirely. This makes the basic skeleton code absolutely tiny! Many people, however, prefer to have a method in case further action is needed in future, and JIT inlining is likely to make the performance identical. (Note that the static constructor itself is still required if you require laziness.)

Fifth version - fully lazy instantiation

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(); 
      }
} 

Here, instantiation is triggered by the first reference to the static member of the nested class, which only occurs in GetInstance. This means the implementation is fully lazy, but has all the performance benefits of the previous ones. Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here. That doesn't raise any other problems, though, as the class itself is private. The code is a bit more complicated in order to make the instantiation lazy, however.

Performance vs laziness
In many cases, you won't actually require full laziness - unless your class initialization does something particularly time-consuming, or has some side-effect elsewhere, it's probably fine to leave out the explicit static constructor shown above. This can increase performance as it allows the JIT compiler to make a single check (for instance at the start of a method) to ensure that the type has been initialized, and then assume it from then on. If your singleton instance is referenced within a relatively tight loop, this can make a significant performance difference. You should decide whether or not fully lazy instantiation is required, and document this decision appropriately within the class. Conclusion
There are various different ways of implementing the singleton pattern in C#. The final two are generally best, as they are thread-safe, simple, and perform well. I would personally use the fourth implementation unless I had some other static members which really shouldn't trigger instantiation, simply because it's the simplest implementation, which means I'm more likely to get it right. The laziness of initialization can be chosen depending on the semantics of the class itself.



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章