下面是个人理解的单例模式:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication6 { public sealed class Singleton { static Singleton instance; /// <summary> /// 为了避免实例不唯一,构造方法私有化 /// </summary> private Singleton() { } public static Singleton Instance { get { return instance == null ? new Singleton() : instance; } } public void dd(){ Console.WriteLine("fdd"); Console.ReadLine(); } } }
主方法调用如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication6 { class Program { static void Main(string[] args) { Singleton.Instance.dd(); } } }
当然这有时候不能保证单例唯一,可以用lock方法来实现如下:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication6 { public sealed class Singleton { static Singleton instance; static readonly object padlock = new object(); public Singleton() { } public static Singleton Instance { get { if (instance == null) { lock (padlock) { if (instance == null) { instance=new Singleton() ; } } } return instance; } } public void dd() { Console.WriteLine("fdd"); Console.ReadLine(); } } }
欢迎交流