c# 单例模式(Single)

 

 public class Singleton
    {
        private static Singleton _instance;
        private static readonly object syn = new object();
        private Singleton() //构造函数设置private,不能被new,单例模式
        {

        }
        public static Singleton CreateInstance()
        {
            if (_instance == null)
            {
                lock (syn)  //加锁防止多线程
                {
                    if (_instance == null)
                    {
                        _instance = new Singleton();
                    }
                }
            }
            return _instance;
        }
    }

 

c# 单例模式(Single)

上一篇:条件变量


下一篇:顺序结构和循环语句