zoukankan      html  css  js  c++  java
  • C#单例模式的三种写法转载

    http://sexycoding.javaeye.com/blog/669942

    第一种最简单,但没有考虑线程安全,在多线程时可能会出问题,不过俺从没看过出错的现象,表鄙视我……

    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();
    }  
    哦,shit!

  • 相关阅读:
    Autoit对win系统弹窗的操作
    Linux服务器测试网络连通性
    如何给linux配置两个不同网段的ip
    记下看过并觉得非常有用的文章
    使用python+selenium对12306车票数据读取
    windows系统mysql安装
    Python使用正则匹配re实现eval计算器
    css3[补1]
    Javascript[2]
    Javascript[1]
  • 原文地址:https://www.cnblogs.com/hl3292/p/1934275.html
Copyright © 2011-2022 走看看