一、定义
从“单例”字面意思上理解为一个类只有一个实例。官方定义:确保一个类只有一个实例,并提供一个全局访问点。
二、实现
下面以实现一个日志记录类为例,描述单例模式。
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:TempLogFilesFilamentCalibration"; 12 13 private string logFullPath; 14 15 private Logger(string pLogFolderName = @"C:TempLogFilesFilamentCalibration") 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:TempLogFilesFilamentCalibration") 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 }