有时候我们常常要在多处使用某一个类里的方法,但是若每一处都new一个实例实在是很耗系统资源的。这样重复的定义式很浪费,这时编程中的“单例模式”就应运而生了。
单例模式的特点就是虽然在多处使用,但使用的却是一个实例,请看下面代码它是如何办到的
using System; using System.Collections.Generic; using System.Text; namespace 单例模式 { class Program { static void Main(string[] args) { Singleton s1 = Singleton.GetInstance(); Singleton s2 = Singleton.GetInstance(); if (s1 == s2) { Console.WriteLine("Objects are the same instance"); } Console.Read(); } } class Singleton { private static Singleton instance; private static readonly object syncRoot = new object(); //将构造函数弄成private,使得无法通过new来实例化这个类 private Singleton() { } public static Singleton GetInstance() { if (instance == null) { lock (syncRoot) { if (instance == null) { instance = new Singleton(); } } } return instance; } } }运行的结果输出:
Objects are the same instance
定义一个单例模式的类需要以下两步:
第一步:将其无参构造函数定义成pirvate类型,使得外部调用时无法通过new定义一个无参的实例对象
private Singleton() { }第二步:定义一个public static类型的方法,这个方法返回的类型是这个类的类型。这个方法的作用就是实例化对象,若对象为空,则new一个实例,否则返回当前实例。
public static Singleton GetInstance() { if (instance == null) { lock (syncRoot) { if (instance == null) { instance = new Singleton(); } } } return instance; }