zoukankan      html  css  js  c++  java
  • 结合项目实例 回顾传统设计模式(五)单例模式

    这个...... 大家应该熟的不能再熟了 虫子就不班门弄斧了

    private static object LockKey = new object();
            private static T _Instance;

            public static T GetInstance()
            {
                return GetInstance(null);
            }

            public static T GetInstance(Func<T> onCreateInstance)
            {
                if (_Instance == null)
                {
                    lock (LockKey)
                    {
                        if (_Instance == null)
                        {
                            try
                            {
                                if (onCreateInstance == null)
                                    _Instance = new T();
                                else
                                    _Instance = onCreateInstance();
                            }
                            catch
                            {
                                _Instance = default(T);
                            }
                        }
                    }
                }
                return _Instance;
            }


            public static T GetInstance(object lockKey, T instance, Func<T> onCreateInstance)
            {
                if (instance == null)
                {
                    if (lockKey == null)
                        lockKey = LockKey;
                    lock (lockKey)
                    {
                        if (instance == null)
                        {
                            try
                            {
                                if (onCreateInstance == null)
                                    instance = new T();
                                else
                                    instance = onCreateInstance();
                            }
                            catch
                            {
                                instance = default(T);
                            }
                        }
                    }
                }
                return instance;
            }

    直接总结:单例模式确保一个类只有一个实例,并提供一个全局访问点

    原创作品允许转载,转载时请务必以超链接形式标明文章原始出处以及作者信息。
    作者:熬夜的虫子
    点击查看:博文索引
  • 相关阅读:
    python拆分pubchem SDF文件
    zlib压缩爬虫采集到的网页源码保存到mongodb减少存储空间
    openresty (lua-nginx_static_merger)合并css js文件 减少请求次数,提升页面速度
    scrapy采集—爬取中文乱码,gb2312转为utf-8
    不写代码的爬虫
    爬虫如何发现更多的url呢,怎么动态收集新的url连接
    python 将GIF拆分成图片方法
    Linux shell循环遍历
    iOS 11 导航栏放置UISearchBar 导航栏高度变高解决办法 (iPhone X出现的情况)
    隐藏UISearchBar中的删除按钮
  • 原文地址:https://www.cnblogs.com/dubing/p/2198925.html
Copyright © 2011-2022 走看看