zoukankan      html  css  js  c++  java
  • C#设计模式--单例模式

    目的:避免对象的重复创建

    单线程具体的实现代码

        /// <summary>
        /// 私有化构造函数
        /// </summary>
        public class Singleton
        {
            private Singleton()
            {//构造函数可能耗时间,耗资源
    
            }
            public static Singleton CreateInstance()
            {
                if (_Singleton == null)
                {
                    _Singleton = new Singleton();
                }
                return _Singleton;
            }
        }
    View Code

    多线程具体的实现代码--双if加lock

        /// <summary>
        /// 私有化构造函数
        /// 私有静态变量保存对象
        /// </summary>
        public class Singleton
        {
    
            private Singleton()
            {//构造函数可能耗时间,耗资源
    
            }
    
            private static Singleton _Singleton = null;
            private static readonly object locker = new object();//加锁
            //双if加lock
            public static Singleton CreateInstance()
            {
                if (_Singleton == null)//保证对象初始化之后不需要等待锁
                {
                    lock (locker)//保证只有一个线程进去判断
                    {
                        if (_Singleton == null)
                        {
                            _Singleton = new Singleton();
                        }
                    }
                }
                return _Singleton;
            }
        }
    View Code

     另外的实现方法

    第一种:

        public class SingletonSecond
        {
    
            private SingletonSecond()
            {//构造函数可能耗时间,耗资源
              
            }
         
            private static SingletonSecond _Singleton = null;
            static SingletonSecond()//静态构造函数,由CLR保证在第一次使用时调用,而且只调用一次
            {
                _Singleton = new SingletonSecond();
            }
            public static SingletonSecond CreateInstance()
            {
                return _Singleton;
            }
        }
    View Code

    第二种:

     public class SingletonThird
        {
    
            private SingletonThird()
            {//构造函数可能耗时间,耗资源
               
            }
           
            private static SingletonThird _Singleton = new SingletonThird();
            public static SingletonThird CreateInstance()
            {
                return _Singleton;
            }
        }
    View Code
  • 相关阅读:
    Git和Github的基本操作
    整合Flask中的目录结构
    自定义Form组件
    flask-script组件
    flask-session组件
    flask中的wtforms使用
    补充的flask实例化参数以及信号
    用flask实现的分页
    用flask的扩展实现的简单的页面登录
    【字符串】【扩展kmp算法总结~~】
  • 原文地址:https://www.cnblogs.com/chen916/p/7641659.html
Copyright © 2011-2022 走看看