第一种
//在方法里new ,这里使用 双if-lock public class SingleFirst { private static SingleFirst _SingleFirst; private static readonly object _Single_Lock = new object(); private SingleFirst() { } public static SingleFirst GetInstance() { if(_SingleFirst == null) { lock (_Single_Lock) { if(_SingleFirst == null) { _SingleFirst = new SingleFirst(); } } } return _SingleFirst; } }
第二种
/// <summary> /// 在构造函数里new(), 在方法返回 /// </summary> public class SingleSecond { private static SingleSecond _SingleSecond = null; private SingleSecond() { } static SingleSecond() { _SingleSecond = new SingleSecond(); } public static SingleSecond GetInstance() { return _SingleSecond; } }
第三种
/// <summary> /// 在静态字段里new(),方法里返回 /// </summary> public class SingleThrid { private static SingleThrid _SingleThird = new SingleThrid(); private SingleThrid() { } public static SingleThrid GetInstance() { return _SingleThird; } }
运行测试
var a1 = SingleFirst.GetInstance(); var a2 = SingleFirst.GetInstance(); Console.WriteLine($"a1 和 a2 是同一实例:{ object.ReferenceEquals(a1, a2)}"); ; var b1 = SingleSecond.GetInstance(); var b2 = SingleSecond.GetInstance(); Console.WriteLine($"b1 和 b2 是同一实例:{ object.ReferenceEquals(a1, a2)}"); var c1 = SingleThrid.GetInstance(); var c2 = SingleThrid.GetInstance(); Console.WriteLine($"c1 和 c2 是同一实例:{ object.ReferenceEquals(a1, a2)}");
源码下载:https://gitee.com/weilong2020/csharp_23_-design-patterns.git