设计模式--单例

1:简单的单例模式

写一个静态方法,一个静态字段

private static Singleton _singleton = null;
public static Singleton CreateSingleton() 
{
   if (_singleton==null)
   {
        _singleton = new Singleton();
   }
   return _singleton;
}

2:通过静态构造函数或者静态字段的写的单例

静态构造函数

static Singleton2() 
        {
            _singleton = new Singleton2();
        }
        private static Singleton2 _singleton = null;
        public static Singleton2 CreateSingleton()
        {
            return _singleton;
        }

静态字段

  private static Singleton3 _singleton = new Singleton3();
        public static Singleton3 CreateSingleton()
        {
            return _singleton;
        }

3:多线程情况下可能会用到线程锁

  增加一个只读的object对象确保多线程情况下每次只有一个线程进入

  private static Singleton1 _singleton = null;
        private static readonly object Singleton1_lcok = new object();
        public static Singleton1 CreateSingleton() 
        {
            lock (Singleton1_lcok)
            {
                if (_singleton == null)
                {
                    _singleton = new Singleton1();
                }
            }
            return _singleton;
        }

上一篇:在mysql8.0 workbench中写SQL语句输入上下标


下一篇:MySql数据库基础知识(包括workbench)