zoukankan      html  css  js  c++  java
  • .NET设计模式实例之单例模式( Singleton Pattern)

         一、单例模式简介(Brief Introduction)

      单例模式(Singleton Pattern),保证一个类只有一个实例,并提供一个访问它的全局访问点。单例模式因为Singleton封装它的唯一实例,它就可以严格地控制客户怎样访问它以及何时访问它。

      二、解决的问题(What To Solve)

      当一个类只允许创建一个实例时,可以考虑使用单例模式。      

      三、单例模式分析(Analysis)1、单例模式结构

    .Net设计模式实例之单例模式( Singleton Pattern)

      Singleton类,定义一个私有变量instance;私有构造方法Singleton()和方法GetInstance();

      私有变量instance:

      private static Singleton instance;

      私有构造方法Singleton(),外界不能使用new关键字来创建此类的实例了。

    private Singleton()
    {
    }

      方法GetInstance(), 此方法是本类实例的唯一全局访问点。

    public static Singleton GetInstance()
    {
        //如实例不存在,则New一个新实例,否则返回已有实例
        if (instance == null)
        {
            instance = new Singleton();
        }
        return instance;
    }

      2、代码

      1、单例模式类Singleton

    public class Singleton
    {
        private static Singleton instance;
     
        /// <summary>
        /// 程序运行时,创建一个静态只读的进程辅助对象
        /// </summary>
        private static readonly object _object = new object();
     
        /// <summary>
        /// 构造方法私有,外键不能通过New类实例化此类
        /// </summary>
        private Singleton()
        {
        }
        /// <summary>
        /// 此方法是本类实例的唯一全局访问点
        /// (双重加锁 Double-Check Locking)
        /// </summary>
        /// <returns></returns>
        public static Singleton GetInstance()
        {
            //先判断实例是否存在,不存在再加锁处理
            if (instance == null)
            {
                //在同一时刻加了锁的那部分程序只有一个线程可以进入,
                lock (_object)
                {
                    //如实例不存在,则New一个新实例,否则返回已有实例
                    if (instance == null)
                    {
                        instance = new Singleton();
                    }
                }
            }
            return instance;
        }
    }

     2、客户端代码

    static void Main(string[] args)
    {
        Singleton singleton1 = Singleton.GetInstance();
        Singleton singleton2 = Singleton.GetInstance();
        if (singleton1 ==singleton2)
        {
            Console.WriteLine("实例singleton1与实例singleton2相同!");
        }
        Console.ReadKey();
    }

      3、实例运行结果

    .Net设计模式实例之单例模式( Singleton Pattern)

      四.实例分析(Example)1、场景

      Mail发送机制中,需要对已经发送的消息做Log。同一时间内只允许一个进程对Txt文档进行操作,此时使用单例模式比较合适。结构如下图所示

    .Net设计模式实例之单例模式( Singleton Pattern)

      WriteMailLog(string message) 方法:纪录Mail发送日志到文件.

      _helper 、_fileLock:程序运行时,创建2个静态只读的进程辅助对象

      2、代码

      1、类MailLog

    public class EmailLog
    {
        private static object _helper = new object();
        private static EmailLog _instance;
        private static object _fileLock = new object();
     
        private EmailLog()
        {}
     
        public static EmailLog GetInstance()
        {
            lock (_helper)
            {
                if (_instance == null)
                {
                    _instance = new EmailLog();
                }
            }
            return _instance;
        }
     
        /// <summary>
        /// 发送Mail日志
        /// </summary>
        /// <param name="message">信息</param>
        public void WriteEmailLog(string message)
        {
            string filePath = System.AppDomain.CurrentDomain.BaseDirectory + "mail.txt";
            StreamWriter sw = null;
            FileStream fs = null;
            lock (_fileLock)
            {
                if (!File.Exists(filePath))
                {
                    fs = System.IO.File.Create(filePath);
                    sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.WriteLine("--------------------------------------------------------------------------");
                    sw.WriteLine(message);
                    sw.Flush();
                    sw.Close();
                }
                else
                {
                    fs = new FileStream(filePath, FileMode.Append);
                    sw = new StreamWriter(fs, Encoding.UTF8);
                    sw.WriteLine("--------------------------------------------------------------------------");
                    sw.WriteLine(message);
                    sw.Flush();
                    sw.Close();
                }
            }
        }
    }

      2、客户端代码

    static void Main(string[] args)
    {
        EmailLog w1 = EmailLog.GetInstance();
        w1.WriteEmailLog("发送Mail给灵动生活...");
        EmailLog w2 = EmailLog.GetInstance();
        w2.WriteEmailLog("发送Mail给James Hao...");
    }

      3、实例运行结果

    .Net设计模式实例之单例模式( Singleton Pattern)

      五、总结(Summary)

      本文对单例模式(Singleton Pattern)的概念及其设计结构图简单地进行了描述,同样也以一个Mail机制的LOG实例进行了说明。单例模式是比较常用。比较简单的设计模式

  • 相关阅读:
    后缀自动机/回文自动机/AC自动机/序列自动机----各种自动机(自冻鸡) 题目泛做
    BZOJ 1001 狼抓兔子 (网络流最小割/平面图的对偶图的最短路)
    FFT与多项式、生成函数题目泛做
    BZOJ 2243 SDOI 2011染色
    莫队/分块 题目泛做
    Cogs 12 运输问题2 (有上下界网络流)
    可并堆/左偏树 题目泛做
    TC快速搜索在win10下不可用
    (转)Tomcat调优
    (转)Tomcat文件详解
  • 原文地址:https://www.cnblogs.com/xcsn/p/4212304.html
Copyright © 2011-2022 走看看