单例模式
定义:确保一个类只有一个实例,并提供一个全局访问
角色:单例Singleton 类内部创建唯一实例 通过静态方法GetInstance()
实现代码
class Singleton
{
private static Singleton instance = null;//静态私有成员变量
//私有构造函数
private Singleton(){}
//静态公有工厂方法 返回唯一实例
public static Singleton GetInstance()
{
if(instance == null)
instance = new Singleton();
return instance;
}
}
饿汉式单例
定义静态变量的时候实例化单例类 类加载时单例对象已创建
无须考虑多个线程同时访问 会一直占用系统资源
class EagerSingleton
{
private static EagerSingleton instance = new EagerSingleton();//静态私有成员变量
//私有构造函数
private Singleton(){}
//静态公有工厂方法 返回唯一实例
public static Singleton GetInstance()
{
return instance;
}
}
懒汉式单例
第一次调用静态工厂方法时实例化单例类 类加载时单例对象已创建
实现延迟加载 无须一直占用系统资源
class LazySingleton
{
private static LazySingleton instance = null;//静态私有成员变量
private static readonly object syncRoot = new object();
//私有构造函数
private Singleton(){}
//静态公有工厂方法 返回唯一实例 双重检查锁定
public static LazySingleton GetInstance()
{
if(instance==null)
{
lock(syncRoot)
{
if(instance==null)
{
instance=new LazySingleton();
}
}
}
return instance;
}
}