getting db connection through singleton class

前端 未结 6 1777
Happy的楠姐
Happy的楠姐 2020-11-30 02:38

I have created an singleton class, this class returns a database connection. So my question is this connection is also satisfying singleton criteria?
If no, than how I c

6条回答
  •  感动是毒
    2020-11-30 03:13

    In .NET C# you can wrtie your singleton like this

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

    or for multi threaded environment:

    using System;
    
    public sealed class Singleton
    {
       private static volatile Singleton instance;
       private static object syncRoot = new Object();
    
       private Singleton() {}
    
       public static Singleton Instance
       {
          get 
          {
             if (instance == null) 
             {
                lock (syncRoot) 
                {
                   if (instance == null) 
                      instance = new Singleton();
                }
             }
    
             return instance;
          }
       }
    }
    

提交回复
热议问题