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;
            }

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

    原创作品允许转载,转载时请务必以超链接形式标明文章原始出处以及作者信息。
    作者:熬夜的虫子
    点击查看:博文索引
  • 相关阅读:
    MySQL数据库详解(二)执行SQL更新时,其底层经历了哪些操作?
    MySQL数据库详解(一)执行SQL查询语句时,其底层到底经历了什么?
    网页静态化解决方案Freemarker
    好久没来看看了~
    springmvc(五) 数据回显与自定义异常处理器
    springmvc(四) springmvc的数据校验的实现
    springmvc(三) 参数绑定、
    springmvc(二) ssm框架整合的各种配置
    springmvc(一) springmvc框架原理分析和简单入门程序
    cursor:pointer 什么意思?
  • 原文地址:https://www.cnblogs.com/dubing/p/2198925.html
Copyright © 2011-2022 走看看