有时候我们常常要在多处使用某一个类里的方法,但是若每一处都new一个实例实在是很耗系统资源的。这样重复的定义式很浪费,这时编程中的“单例模式”就应运而生了。

单例模式的特点就是虽然在多处使用,但使用的却是一个实例,请看下面代码它是如何办到的

 

 
  
  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Text;   
  4.    
  5. namespace 单例模式   
  6. {   
  7.     class Program   
  8.     {   
  9.         static void Main(string[] args)   
  10.         {   
  11.             Singleton s1 = Singleton.GetInstance();   
  12.             Singleton s2 = Singleton.GetInstance();   
  13.    
  14.             if (s1 == s2)   
  15.             {   
  16.                 Console.WriteLine("Objects are the same instance");   
  17.             }   
  18.    
  19.             Console.Read();   
  20.         }   
  21.     }   
  22.    
  23.    
  24.     class Singleton   
  25.     {   
  26.         private static Singleton instance;   
  27.         private static readonly object syncRoot = new object();   
  28.         //将构造函数弄成private,使得无法通过new来实例化这个类   
  29.         private Singleton()   
  30.         {   
  31.         }   
  32.    
  33.         public static Singleton GetInstance()   
  34.         {   
  35.             if (instance == null)   
  36.             {   
  37.    
  38.                 lock (syncRoot)   
  39.                 {   
  40.    
  41.                     if (instance == null)   
  42.                     {   
  43.                         instance = new Singleton();   
  44.                     }   
  45.                 }   
  46.             }   
  47.             return instance;   
  48.         }   
  49.    
  50.     }   
  51.    
  52. }   

运行的结果输出:

 

Objects are the same instance

定义一个单例模式的类需要以下两步:

第一步:将其无参构造函数定义成pirvate类型,使得外部调用时无法通过new定义一个无参的实例对象

 

 
  
  1. private Singleton()   
  2. {   
  3. }   

 

第二步:定义一个public static类型的方法,这个方法返回的类型是这个类的类型。这个方法的作用就是实例化对象,若对象为空,则new一个实例,否则返回当前实例。

 

 
  
  1. public static Singleton GetInstance()   
  2.         {   
  3.             if (instance == null)   
  4.             {   
  5.    
  6.                 lock (syncRoot)   
  7.                 {   
  8.    
  9.                     if (instance == null)   
  10.                     {   
  11.                         instance = new Singleton();   
  12.                     }   
  13.                 }   
  14.             }   
  15.             return instance;   
  16.         }