• C#单例模式的三种写法


    第一种最简单,但没有考虑线程安全,在多线程时可能会出问题 

    public class Singleton
    {
        private static Singleton _instance = null;
        private Singleton(){}
        public static Singleton CreateInstance()
        {
            if(_instance == null)

            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }

    第二种考虑了线程安全,不过有点烦,但绝对是正规写法,经典的一叉 

    public class Singleton
    {
        private volatile static Singleton _instance = null;
        private static readonly object lockHelper = new object();
        private Singleton(){}
        public static Singleton CreateInstance()
        {
            if(_instance == null)
            {
                lock(lockHelper)
                {
                    if(_instance == null)
                         _instance = new Singleton();
                }
            }
            return _instance;
        }
    }

    第三种可能是C#这样的高级语言特有的,实在懒得出奇

    public class Singleton
    {

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

  • 相关阅读:
    ExtJs错误总结
    Java中的基本类型和引用类型(未完)
    【转】JavaScript中的全局变量与局部变量
    地理信息技术在现场项目的应用浅析
    vector的二分查找算法
    Linux命令
    封装 libmemcached
    Linux + boost + libmemcached + jsoncpp + mysql 配置
    SQL字符串处理函数大全(转)
    vector 排序方法sort的使用
  • 原文地址:https://www.cnblogs.com/xcsn/p/4212291.html
Copyright © 2020-2023  润新知