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

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

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

 

相关文章:

  • 2022-02-16
  • 2021-12-02
  • 2022-03-01
  • 2021-10-10
  • 2022-12-23
  • 2021-12-20
  • 2021-06-27
  • 2021-10-29
猜你喜欢
  • 2021-12-14
  • 2021-09-15
  • 2021-11-27
  • 2021-11-19
  • 2021-08-25
  • 2022-02-03
  • 2022-01-01
相关资源
相似解决方案