[置顶] 设计模式之单例模式 (Design patterns of the The singleton pattern)c#

     单例模式饿目的是确保某个类只有一份实例,而且从在一个全局访问点来访问这个实例,这一模式保证类只能被实例化一次,而且所有的请求都使用这个唯一的实例,此外,对象应该在使用的时候才被创建,在单例模式中,实施这种约束的是类本身,而不是类的额客户。

理论代码:

public sealed class Singleton{

//私有构造函数

Singleton(){ }

//通过私有构造函数实例化的私有对象

static readonly Singleton instance=new Singleton();

//获取对象的共有静态属性

public static Singleton UniqueInstance{

get { return instance;}

}

}


单例模式------懒惰式初始化(懒汉模式)

//sealed 阻止发生派生,而派生可能增加实例

public sealed class Singleton{

//私有构造函数

Singleton(){ }

//用于懒惰式初始化的嵌套类

class SingletonCreator(){

static SingletonCreator(){}

//通过私有构造函数实例化的私有对象

internal static readonly Singleton uniqueInstance =new Singleton();

}


public static Singleton UniqueInstance{

get { return SingletonCreator.uniqueInstance;}

}

}


多线程时的单例模式

class Singleton

{

 private static Singleton instance;

 private static readonly object syncRoot=new object();  //创建一个静态只读的进程辅助对象,

 private Singleton()

 {

 }

 public static SingletonGetInstance()

 {

     if(instance==null) // 双重锁定

      {

            //锁定进程 ,当线程位于代码的临界区时,另一个线程不进入临界区,如果其他线程试图进入锁定的代码,它将一直等待,知道该对象释放。

            lock(syncRoot)

            {

                  if(instance==null)  //双重锁定

                   { 

                       instance=new Singleton();

                    }

            }

      }

 

}


}



posted @ 2013-03-11 13:32  shouqiang Wei  阅读(180)  评论(0编辑  收藏  举报