zoukankan      html  css  js  c++  java
  • 关于单例的泛型实现,悲哀啊

    自己在做一个Unity的小项目,想在UI上不使用脚本继承MonoBehavior然后挂在物体上的方式。于是想写一个单例的UIBase类,子类继承UIBase同时也复用UIBase的单例,这样不用每写一个子类就写一遍单例。于是在网上找到不少人写的单例的泛型实现:

        //父类
        public class Person<T> where T : class, new()
        {
            private static T _instance;
            private static readonly object syslock = new object();
            public static T GetInstance()
            {
                if (_instance==null)
                {
                    lock (syslock)
                    {
                        _instance = new T();
                    }
                }
                return _instance;
            }
        }
    
        //子类
        public class Student : Person<Student>
        {
        }
    
        //或者:
        public class Student
        {
            public static Student GetInstance()
            {
                return Person<Student>.GetInstance();
            }
        }
    
        //调用
        Student.GetInstance(); 

    这种写法子类无法私有化构造方法,因为子类作为泛型T必须具有公用的无参构造,完全违背了单例。单例最核心的东西都没理解到,只想着实现GetInstance公用访问就行了!

  • 相关阅读:
    new
    如何在win7上面安装python的包
    进程
    网络编程模块的使用
    面向对象基础与实例
    类与对象的属性与使用方法
    基础面向对象与面向过程
    RE模块垃圾回收机制
    常用函数模块
    thinkphp6 find_in_set使用实例
  • 原文地址:https://www.cnblogs.com/fuyunzzy/p/7863770.html
Copyright © 2011-2022 走看看