zoukankan      html  css  js  c++  java
  • 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
        }
    }
  • 相关阅读:
    OpenGL Pixel Linked-List
    Unity multi_compile
    Bindless Textures
    chmod递归设置文件属性
    push submodule
    NodeJS Debugger
    重载new操作符
    OpenGL瓶颈
    NGUI架构和Draw Call合并原理
    字符串哈希函数(String Hash Functions)
  • 原文地址:https://www.cnblogs.com/sy-liu/p/13088332.html
Copyright © 2011-2022 走看看