What are the real world applications of the singleton pattern?

后端 未结 10 559
南旧
南旧 2021-02-01 07:22

Duplicate

On design patterns: When should I use the singleton?

class Singleton
{
    private static Singleton instance;

    private Singleton() {}

             


        
10条回答
  •  -上瘾入骨i
    2021-02-01 07:52

    Note that this code is not thread safe:

    get   
    {
       if (instance == null)   
          instance = new Singleton();   
        return instance;   
    }   
    

    One thread could enter the function, get past the test for null and then be suspended. A second thread could then start and get past the null test. From that point on, both threads will at some point create their own copy of the sungleton object, only one of which gets used.

    This may not matter so much in a GC language like C#, but if the singleton controls rresources other than memory, then it does matter. You need to use the double-checked locking pattern to prevent it.

提交回复
热议问题