一、单线程
public class Singleton { private static Singleton instance; int x, y; private Singleton() { } public static Singleton Instance { get { if( instance == null ) { instance = new Singleton(); } return 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; } }
二、适用于多线程
public class MultiThreadSingleton { private static volatile MultiThreadSingleton instance = null; private static object lockHelper = new object(); private MultiThreadSingleton() { } public static MultiThreadSingleton Instance { get { if( instance == null ) { lock( lockHelper ) { if( instance == null ) { instance = new MultiThreadSingleton(); } } } return instance; } } }
三、适用于多线程与单线程
public class AllSingleton { public static readonly AllSingleton Instance = new AllSingleton(); private AllSingleton() { } }
四、一个线程安全,懒实现的方式
public sealed class Singleton { private static readonly Lazy<Singleton> instanceHolder = new Lazy<Singleton>(() => new Singleton()); private Singleton() { ... } public static Singleton Instance { get { return instanceHolder.Value; } } }