From the global perspective of the application, if only one instance of the class can be generated, you can consider the singleton mode.
□Real-time loading Singleton Mode
Assign a class instance to a static field of the class.
class Program
{
static void Main(string[] args)
{
Logger log = Logger.GetInstance();
log.WriteToFile();
Console.Read();
}
}
public class Logger
{
private static Logger logger = new Logger();
private Logger(){}
public static Logger GetInstance()
{
return logger;
}
public void WriteToFile()
{
Console. writeline ("the error is written to the file ~~ ");
}
}
□Delayed loading Singleton Mode
The instance of the class is not generated until the static method of the class is called.
public class Logger
{
private static Logger logger = null;
private Logger(){}
public static Logger GetInstance()
{
if (null == logger)
{
logger = new Logger();
}
return logger;
}
public void WriteToFile()
{
Console. writeline ("the error is written to the file ~~ ");
}
}
□Thread-safe Singleton Mode
Until the static method of the class is called, ensure that only one thread enters the instance of the generated class.
public class Logger
{
private static Logger logger = null;
private static object lockObj = new object();
private Logger(){}
public static Logger GetInstance()
{
lock (lockObj)
{
if (logger == null)
{
logger = new Logger();
}
return logger;
}
}
public void WriteToFile()
{
Console. writeline ("the error is written to the file ~~ ");
}
}
Summary: static Singleton-type private fields and private constructor. Acquiring Singleton is a necessary element of Singleton mode.
Use the simplest example to understand Singleton pattern)