天天看点

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

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

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

_helper 、_fileLock:程序运行时,创建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);

}

2、客户端代码

static void Main(string[] args)

    EmailLog w1 = EmailLog.GetInstance();

    w1.WriteEmailLog("发送Mail给灵动生活...");

    EmailLog w2 = EmailLog.GetInstance();

    w2.WriteEmailLog("发送Mail给James Hao...");

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

本文转自 灵动生活 51CTO博客,原文链接:http://blog.51cto.com/smartlife/264524,如需转载请自行联系原作者

继续阅读