using System; namespace SingletonFunc{ public class Singleton{ private static object obj = new object(); private static Singleton singleton; public static Singleton CreateSingleton() { if(singleton == null){ lock(obj) { if(singleton == null) { singleton = new Singleton(); } } } return singleton; } public override bool Equals(object obj) { if(obj == null) return false; if(singleton == obj as Singleton) return true; else return false; } } public class EntryPoint{ public static void Main(string[] args){ Singleton singleton1 = Singleton.CreateSingleton(); Singleton singleton2 = Singleton.CreateSingleton(); // bool compare = System.Object.ReferenceEquals(singleton1,singleton2); bool compare = System.Object.Equals(singleton1,singleton2); compare = singleton1.Equals(singleton2); if(compare){ Console.Write("true"); } else{ Console.Write("false"); } Console.Read(); } } }
设计模式之单例模式代码示例
最新推荐文章于 2024-11-15 09:25:29 发布