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

 

posted @ 2020-06-15 19:00  三里路异乡客  阅读(270)  评论(0编辑  收藏  举报