public class Singleton { private static Singleton Instance; private Singleton() {} public static Singleton Instance { get { if(instance == null) { instance = new Singleton(); } return instance; } } }
public class Singleton { private static Singleton Instance = new Singleton(); private Singleton() {} public static Singleton Instance { get { return instance; } } }
两者有啥区别?
public class Singleton { private static volatile Singleton Instance = ; private static object lockHelper = new Object(); private Singleton() {} public static Singleton Instance { get { if(instance == null) { lock(lockHelper) { if(instance == null) { instance = new Singleton(); } } } return instance; } } }
class Singleton { public static readonly Singleton Instance = new Singleton(); private Singleton() {} }
与
class Singleton { public static readonly Singleton Instance; static Singleton() { Instance = new Singleton(); } private Singleton(); }
public class Singleton { private static Singleton instance; private Singleton(int x, int y) { this.x = x; this.y = y; } public static Singleton GetInstance(int x, int y) { if (instance == null) { instance = new Singleton(x, y); } else { instance.x = x; instance.y = y; } return instance; } }
单例模式——Singleton,布布扣,bubuko.com
原文:http://www.cnblogs.com/9527y/p/3923458.html