简介:单例模式是软件工程中最著名的模式之一。从本质上讲,singleton 是一个只允许创建自身的单个实例的类,并且通常提供对该实例的简单访问。最常见的是,单例不允许在创建实例时指定任何参数 - 否则,对实例进行第二次请求但使用不同的参数可能会出现问题!(如果对于具有相同参数的所有请求,应访问同一实例,则工厂模式更合适。本文仅处理不需要参数的情况。通常,单例的要求是它们是惰性创建的 - 即直到第一次需要实例时才创建实例。
版本1:未考虑线程安全锁(不建议使用)
public class Singleton<T> where T : new()
{
private static T _instance;
private static object Locker = new object();
private string _path;
public static T Instance
{
get
{
if (_instance == null)
{
_instance = new T();
}
return _instance;
}
}
public string Path { get => _path; set => _path = value; }
public void Save()
{
_instance.Serialize(_path);
}
public void Read()
{
_instance = SerializeHelper.Deserialize<T>(_path);
}
}
版本2:单线程安全锁
public class Singleton<T> where T : new()
{
private static T _instance;
private static object Locker = new object();
private string _path;
public static T Instance
{
get
{
lock (Locker)
{
if (_instance == null)
{
_instance = new T();
}
return _instance;
}
}
}
public string Path { get => _path; set => _path = value; }
public void Save()
{
_instance.Serialize(_path);
}
public void Read()
{
_instance = SerializeHelper.Deserialize<T>(_path);
}
}
版本3:尝试使用 Double-Check 的线程安全锁
public class Singleton<T> where T : new()
{
private static T _instance;
private static object Locker = new object();
private string _path;
public static T Instance
{
get
{
if(_instance == null)
{
lock (Locker)
{
if (_instance == null)
{
_instance = new T();
}
}
}
return _instance;
}
}
public string Path { get => _path; set => _path = value; }
public void Save()
{
_instance.Serialize(_path);
}
public void Read()
{
_instance = SerializeHelper.Deserialize<T>(_path);
}
}
使用
public class Configure : Singleton<Configure>
{
}