What are the real world applications of the singleton pattern?

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

Duplicate

On design patterns: When should I use the singleton?

class Singleton
{
    private static Singleton instance;

    private Singleton() {}

             


        
10条回答
  •  温柔的废话
    2021-02-01 08:10

    This is not a singleton as a singleton provides the thread safety with readonly keywords.

    For example,

    public sealed class Singleton
    {
        // private static Singleton instance; (instead of this, it should be like this, see below)
        private static readonly Singleton instance = new Singleton();
    
        static Singleton(){}
    
        private Singleton() {}
    
        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                    instance = new Singleton();
                return instance;
            }
        }
    }
    

    By using this it will provide the tread safety and proper singleton pattern (that is how it is different from a static class). Your code for the singleton were not thread safe.

    For more about singleton, check these links:

    • http://csharpindepth.com/articles/general/singleton.aspx
    • http://aspalliance.com/70_Session_Based_Singleton_Object

提交回复
热议问题