C#设计模式---单例模式(Singleton Pattern)

一、定义

从“单例”字面意思上理解为一个类只有一个实例。官方定义:确保一个类只有一个实例,并提供一个全局访问点。

 

二、实现

下面以实现一个日志记录类为例,描述单例模式。

 1 using System;
 2 using System.IO;
 3 
 4 namespace Utility
 5 {
 6     public class Logger
 7     {
 8         private static Logger loggerInstance = null;
 9         private static readonly object lockObject = new object();
10 
11         private string logFolderName  =@"C:\Temp\LogFiles\FilamentCalibration\";
12 
13         private  string logFullPath;
14 
15         private Logger(string pLogFolderName = @"C:\Temp\LogFiles\FilamentCalibration\")
16         {
17             logFolderName = pLogFolderName;
18             logFullPath = String.Format(logFolderName + "{0:yyyyMMdd HHmmss} FilamentCal.log", DateTime.Now);
19 
20             if (!Directory.Exists(logFolderName))
21             {
22                 Directory.CreateDirectory(logFolderName);
23             }
24         }
25 
26         public static Logger GetLoggerInstance(string pLogFolderName = @"C:\Temp\LogFiles\FilamentCalibration\")
27         {
28             if (loggerInstance == null)
29             {
30                 lock (lockObject)
31                 {
32                     if (loggerInstance == null)
33                     {
34                         loggerInstance = new Logger(pLogFolderName);
35                     }
36                 }
37             }
38             return loggerInstance;
39         }
40 
41         public void WriteLine(string text)
42         {
43             try
44             {
45                 using (StreamWriter myLogger = File.AppendText(logFullPath))
46                 {
47                     myLogger.WriteLine($"[FilaCal {DateTime.Now:HH:mm:ss.fff]} {text}");
48                 }
49             }
50             catch(Exception err)
51             {
52                 throw new Exception(err.Message);
53             }
54         }
55     }
56 }
View Code

 

转载于:https://www.cnblogs.com/3xiaolonglong/p/9609535.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值