• 26、面向对象设计模式之单例模式——泛型单例


    普通懒加载多线程单例

    using System;
    public class Singleton<T> where T : class, new()
    {
        private static volatile T instance;
        private static readonly object syncRoot = new object();
    
        public static T GetInstance()
        {
            if(instance == null)
            {
                lock (syncRoot)
                {
                    if(instance == null)
                    {
                        instance = new T();
                    }
                }
            }
            return instance;
        }
    }
    
    public class MyClass : Singleton<MyClass>
    {
        public void Print()
        {
            Console.WriteLine("Hello World");
        }
    }
    public class Program
    {
        public static void Main(string[] args)
        {
            Singleton<MyClass> s1 = Singleton<MyClass>.GetInstance();
            Singleton<MyClass> s2 = Singleton<MyClass>.GetInstance();
            Console.WriteLine(s1 == s2);
            MyClass.GetInstance().Print();
    
        }
    }

    IODH技术对泛型单例进行改良

     

    public class Singleton<T> where T:new()
    {
        public static T GetInstance(){
            
            return SingletonCreator.instance;
        }
        class SingletonCreator(){
            
            internal static readonly T instance = new T();
        }
    }
    public class MyClass:Singleton<MyClass>{
        
        public void Print(){
            Console.WriteLine("你好,世界")
        }
    }
    public class YourClass:Singleton<YourClass>(){
        public void Print02(){
            
            Console.WriteLine("Hello world")
        }
        
    }
    public class Program
    {
        static void Main(string[] args){
            
            Singleton<MyClass> s1,s2;
            s1 = Singleton<MyClass>.GetInstance();
            s2 = Singleton<MyClass>.GetInstance();
            Console.WriteLine(s1 == s2);//true
            Console.WriteLine(MyClass.GetInstance().Equals(YourClass.GetInstance()));//false
        }
    }
  • 相关阅读:
    学会企业分析
    股票暴跌,收益会更高
    富人?中产?
    学会看财务报表
    财务自由三大核心工具
    理财工具分类
    webpack构建速度和体积极限优化
    将搜索时间设置为23:59:59
    省市区县街道四级联动下拉菜单
    用原生JS实现多张图片上传及预览功能(兼容IE8)
  • 原文地址:https://www.cnblogs.com/sy-liu/p/13088332.html
Copyright © 2020-2023  润新知