• [置顶] 设计模式之单例模式 (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();

                        }

                }

          }

     

    }


    }



  • 相关阅读:
    多线程调用本质
    音频编码解码器库 libZPlay
    C#多线程代码调试技巧
    SharpMap实践代码
    Work Queue based multithreading
    (转)C#写的NoSQL开源系统(系列)
    A .NET State Machine Toolkit Part I
    在线开发环境地址
    数字音乐商KKBOX三季度将进军日本市场
    苹果官方购置iPad用户将获1100元退款
  • 原文地址:https://www.cnblogs.com/wsq724439564/p/3258208.html
Copyright © 2020-2023  润新知