单例模式:
懒汉模式和饿汉模式。
考虑多线程安全问题,以及双重锁定。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Singleton { private static Singleton singleton; private static readonly object syncRoot = new object(); private Singleton() { } public static Singleton GetInstance() { // multiple threading issue // double-check locking if (singleton == null) { lock (syncRoot) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } } sealed class SingletonB { private static readonly SingletonB instance = new SingletonB(); private SingletonB() { } public static SingletonB GetInstance() { return instance; } } class Program { static void Main(string[] args) { Singleton s1 = Singleton.GetInstance(); Singleton s2 = Singleton.GetInstance(); if(s1 == s2) { Console.WriteLine("Equals."); } Console.ReadLine(); } } }