【设计模式】 单例模式 (类只允许实例化一次)
一. 代码实现
1. 私有构造函数 + 私有静态变量 + 公开静态函数
a. 代码简洁,但使用静态变量和静态函数会一直占用内存,不过已现在的硬件配置,无所谓了
b. 代码
private SingletonClass() { }
private static SingletonClass Instance = new SingletonClass();
public static SingletonClass GetInstance()
{
return Instance;
}
2. 双判断 + 单锁
private static SingletonClass _instance; private static readonly object LockObj = new object(); public static SingletonClass GetInstance() { if (_instance == null) { lock (LockObj) { if (_instance == null) { _instance = new SingletonClass(); } } } return _instance; }
3. 泛型单例
public class Singleton<T> where T : new() { private static T _instance = new T(); private static readonly object _lockObj = new object(); private Singleton(){} public static T GetInstance() { if (_instance == null) { lock (_lockObj) { if (_instance == null) { _instance = new T(); } } } return _instance; } }
二. 使用场景
1. 顾名思义,一个类只允许拥有一个实例