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!

  • 相关阅读:
    经典SQL语句大全
    《构建高性能Web站点》观后感
    网搜索引擎架构设计
    使用Windows系统的几个好的习惯
    静态页面对seo优化之详解
    让您SEO学习时间缩短一半的高阶秘籍
    java链表
    GAE 数据存储——事务
    GAE 博客——B3log Solo 0.2.0 发布了!
    Wine 1.3.7 发布
  • 原文地址:https://www.cnblogs.com/gc2013/p/3753196.html
Copyright © 2011-2022 走看看