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版本回退 reset
    三门问题 概率论
    如何高效的学习高等数学
    数据库6 关系代数(relational algebra) 函数依赖(functional dependency)
    数据库5 索引 动态哈希(Dynamic Hashing)
    数据库4 3层结构(Three Level Architecture) DBA DML DDL DCL DQL
    梦想开始的地方
    java String字符串转对象实体类
    java 生成图片验证码
    java 对象之间相同属性进行赋值
  • 原文地址:https://www.cnblogs.com/chen916/p/7641659.html
Copyright © 2011-2022 走看看