zoukankan      html  css  js  c++  java
  • 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();
    }  
    哦,shit!

    转:http://shansun123.iteye.com/blog/669942

  • 相关阅读:
    P1587 [NOI2016]循环之美 杜教筛
    【学习笔记】省选动态规划类型选讲
    【模板】结构体重载高精度
    SP1716 GSS3
    SP1043 GSS1
    P1890 gcd区间 线段树
    【模板】(最小费用)最大流
    【模板】矩阵乘法
    P1073 最优贸易 DFS
    【2019.8.14】2019QB学堂DP图论班第一次考试 Problem C
  • 原文地址:https://www.cnblogs.com/stalwart/p/3011715.html
Copyright © 2011-2022 走看看