zoukankan      html  css  js  c++  java
  • 单列模式(泛型版)

    View Code
     public static class SingletonProvider<T> where T : new()
        {
            
    private static T m_instance;
            
    private static readonly object sync = new object();
            
    /// <summary>
            
    /// 不够构造函数的泛型单列
            
    /// </summary>
            public static T Instance
            {
                
    get
                {
                    
    if (m_instance == null)
                    {
                        
    lock (sync)
                        {
                            
    if (m_instance == null)
                            {
                                
    try
                                {
                                    m_instance 
    = new T();
                                }
                                
    catch
                                {
                                }
                            }
                        }
                    }
                    
    return m_instance;
                }
            }
            
    /// <summary>
            
    /// 带构造函数的泛型单列模式
            
    /// </summary> 
            public static T InstanceForParameter(params object[] objarr)
            {

                
    if (m_instance == null)
                {
                    
    lock (sync)
                    {
                        
    if (m_instance == null)
                        {
                            var t 
    = typeof(T);
                            var tp 
    = new Type[objarr.Length];
                            
    for (int i = 0; i < objarr.Length; i++)
                            {
                                tp[i] 
    = objarr[i].GetType();
                            }
                            
    try
                            {
                                System.Reflection.ConstructorInfo ci 
    = t.GetConstructor(tp);
                                m_instance 
    = (T)ci.Invoke(objarr);
                            }
                            
    catch
                            {
                            }

                        }
                    }
                }
                
    return m_instance;
            }
        }
  • 相关阅读:
    2020寒假 学习进度笔记4:spark使用1
    2020寒假 学习进度笔记3:Spark安装
    2020寒假 学习进度笔记2:Scala学习
    2020寒假 学习进度笔记1:Scala安装(Windows + Lunux)
    测试试卷—数据清洗
    实验6:Mapreduce实例——WordCount
    个人课程总结
    如何打jar包
    初探性能优化——2个月到4小时的性能提升(copy)推荐阅读
    《阿里巴巴Java工作手册》学习笔记
  • 原文地址:https://www.cnblogs.com/jacd/p/1771136.html
Copyright © 2011-2022 走看看