代码改变世界

单件模式

2010-08-26 22:25  Clingingboy  阅读(875)  评论(0编辑  收藏  举报

保证一个类仅有一个实例,并提供一个访问它的全局访问点。

image_2


1.示例1.
由于加了readonly关键字,所以只会在构造函数中初始化一次.

public sealed class Singleton {
   // Private Constructor 
   Singleton() { }
   
   // Private object instantiated with private constructor
   static readonly Singleton instance = new Singleton();
 
   // Public static property to get the object
   public static Singleton UniqueInstance {
     get { return instance;}
   }
 }


2.延迟初始化

注意内部多定义了一个类

public class Singleton {
   // Private constructor 
   Singleton () { }
   
   // Nested class for lazy instantiation
   class SingletonCreator {
     static SingletonCreator () {}
     // Private object instantiated with private constructor
     internal static readonly 
     Singleton uniqueInstance = new Singleton();
   }
 
   // Public static property to get the object
   public static Singleton UniqueInstance {
     get {return SingletonCreator.uniqueInstance;}
   }
 }

这个模式平时用到的也最多,面试的人也很喜欢问这个,属于基本模式,简单也不容易忘记,自然大家都喜欢问,呵呵