学习设计模式,一直没有机会写一个单例模式。
今天在控制台应用程序,写个简单的例子,Hi与Hello。
public sealed class At { private static At instance = null; public static At Instance { get { if (instance == null) { instance = new At(); } return instance; } } public void Hello() { Console.WriteLine("Hello"); } public void Hi() { Console.WriteLine("Hi"); } }
单例类,宣告为sealed,也就是说阻止其他类从该类继承。对象只是本身。
public sealed class At { private static At instance = null; private static readonly object threadSafeLock = new object(); public static At Instance { get { lock (threadSafeLock) { if (instance == null) { instance = new At(); } return instance; } } } public void Hello() { Console.WriteLine("Hello"); } public void Hi() { Console.WriteLine("Hi"); } }
下面内容于2017-12-12 08:10分添加:
补充,上面的写法是每次加锁,性能多少有些损失。 解决此问题可以加个判断对象没有实例化时加锁。
public static At Instance { get { if (instance == null) { lock (threadSafeLock) { if (instance == null) { instance = new At(); } } } return instance; } }