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();
    }  
  • 相关阅读:
    centos8.2安装nginx
    Centos8安装PostgreSQL
    PostgreSQL 安装时提示下载元数据失败
    MySQL8定时备份
    Centos8安装Docker
    Centos8安装中文字体
    Centos8源码安装libgdiplus
    MySQL拖拽排序
    MySQL8修改事务隔离级别
    MySQL启动问题
  • 原文地址:https://www.cnblogs.com/zhengqian/p/8915667.html
Copyright © 2011-2022 走看看