zoukankan      html  css  js  c++  java
  • 泛型单列

    不支持非公共的无参构造函数:
    public abstract class BaseInstance where T : class,new()
    {
    private readonly static object lockObj = new object();
    private static T instance = null;
    public static T Instance
    {
    get
    {
    if (instance == null)
    {
    lock (lockObj)
    {
    if (instance == null)
    {
    instance = new T();
    }
    }
    }
    return instance;
    }
    }
    }

    支持非公共的无参构造函数:
    public class BaseInstance where T : class//new(),new不支持非公共的无参构造函数
    {
    /*
    * 单线程测试通过!
    * 多线程测试通过!
    * 根据需要在调用的时候才实例化单例类!
    */
    private static T _instance;
    private static readonly object SyncObject = new object();
    public static T Instance
    {
    get
    {
    if (_instance == null)//没有第一重 singleton == null 的话,每一次有线程进入 GetInstance()时,均会执行锁定操作来实现线程同步,
    //非常耗费性能 增加第一重singleton ==null 成立时的情况下执行一次锁定以实现线程同步
    {
    lock (SyncObject)
    {
    if (_instance == null)//Double-Check Locking 双重检查锁定
    {
    //_instance = new T();
    //需要非公共的无参构造函数,不能使用new T() ,new不支持非公共的无参构造函数
    _instance = (T)Activator.CreateInstance(typeof(T), true); //第二个参数防止异常:“没有为该对象定义无参数的构造函数。”
    }
    }
    }
    return _instance;
    }
    }
    public static void SetInstance(T value)
    {
    _instance = value;
    }
    }

  • 相关阅读:
    声明对象指针,调用构造、析构函数的多种情况
    [C++ STL] 常用算法总结
    [C++ STL] map使用详解
    [C++ STL] set使用详解
    [C++ STL] list使用详解
    [C++ STL] deque使用详解
    Servlet课程0424(一) 通过实现Servlet接口来开发Servlet
    CSS盒子模型
    Spring学习之第一个hello world程序
    Java基础面试题
  • 原文地址:https://www.cnblogs.com/LCLBook/p/15493764.html
Copyright © 2011-2022 走看看