关于单例模式的一个小demo,在多线程访问中,为了实例唯一,所以object锁定下。
using System;
using System.Collections.Generic;using System.Text;class Singleton
{private static object lockHelper = new object();
private static volatile Singleton instance = null; private string _myName;public string MyName
{ get { return _myName; } set { _myName = value; } }private Singleton()
{ _myName = "leon"; }public static Singleton GetInstance()
{ if (instance == null) { lock (lockHelper) { if (instance == null) { instance = new Singleton(); } } } return instance;}
}
class Program
{ static void Main(string[] args) { Console.WriteLine(Singleton.GetInstance().MyName); Console.ReadLine(); }}