单例模式:保证一个类只有一个实例,并提供给它一个全局访问点。也就是说实例要么没有,有也只能是一个。
1、最简单的单例模式
class Singleon { private static Singleon instance; private Singleon() { } public static Singleon GetInstance() { if (instance == null) { instance = new Singleon(); } return instance; } }
客户端代码
private static void SingleModeTest() { Singleon s1 = Singleon.GetInstance(); Singleon s2 = Singleon.GetInstance(); if (s1 == s2) { Console.WriteLine("两个对象实例是相等的"); } }
缺点:在多线程中还是会创建多个实例的。
2、 多线程下解决被多个实例
class SingleonMultiThread { private static SingleonMultiThread instance; private static readonly object syncRoot = new object(); private SingleonMultiThread() { } public static SingleonMultiThread GetInstance() { if (instance == null) { lock (syncRoot) { if (instance == null) { instance = new SingleonMultiThread(); } } } return instance; } }
3、采用静态初始化变量的方法
sealed class SingleonStaticInit { private static SingleonStaticInit instance = new SingleonStaticInit(); private SingleonStaticInit() { } public static SingleonStaticInit GetInstance() { return instance; } }
采用静态初始化方法,不需要显示的编写线程安全代码,即可解决多线程环境下不安全问题。第三中方法最好。