单例模式(Singleton Pattern)
1)利用一个静态变量来记录Singleton类的唯一实例;
1)将GetInstance()方法变成同步(synchronized)的方法。为了同步,该处理方式会影响程序性能;
2)用“双重检测加锁”( double-checked locking),在GetInstance()方法中减少同步使用;
3)使用“急切”(eager)方式创建实例,而不用延迟实例化的做法。
C#中使用“静态初始化”方式,将实例变量标记为readonly,意味着只能在静态初始化期间或在类的构造器中分配变量。这种静态初始化的方式是在自己被 加载时就将自己实例化,所以被称为 饿汉式单例类;前面的实现方式是在 第一次被应用时,才将自己实例化,所以被称为 懒汉式单例。
确保一个类只有一个实例,并提供一个全局访问点。
1)利用一个静态变量来记录Singleton类的唯一实例;
2)将构造器声明为私有的;
3)使用GetInstance()方法实例化对象,并返回该实例(全局访问点)。
class Singleton
{
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton GetInstance()
{
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
#if LANGUAGE_CPP
class Singleton
{
public:
static Singleton *GetInstance();
protected:
Singleton();
private:
static Singleton *uniqueInstance;
}
Singleton *Singleton::uniqueInstance = null;
Singleton *Singleton::GetInstance()
{
if (uniqueInstance == null)
{
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
#endif
2、处理多线程
1)将GetInstance()方法变成同步(synchronized)的方法。为了同步,该处理方式会影响程序性能;
2)用“双重检测加锁”( double-checked locking),在GetInstance()方法中减少同步使用;
3)使用“急切”(eager)方式创建实例,而不用延迟实例化的做法。
C#中使用“静态初始化”方式,将实例变量标记为readonly,意味着只能在静态初始化期间或在类的构造器中分配变量。这种静态初始化的方式是在自己被 加载时就将自己实例化,所以被称为 饿汉式单例类;前面的实现方式是在 第一次被应用时,才将自己实例化,所以被称为 懒汉式单例。
class SingletonMT
{
private static SingletonMT uniqueInstance;
private static readonly object syncRoot = new object();
private SingletonMT() { }
public static SingletonMT GetInstance()
{
lock (syncRoot)
{
if (uniqueInstance == null)
{
uniqueInstance = new SingletonMT();
}
}
return uniqueInstance;
}
}
// double-checked locking
class SingletonDL
{
private static SingletonDL uniqueInstance;
private static readonly object syncRoot = new object();
private SingletonDL() { }
public static SingletonDL GetInstance()
{
if (uniqueInstance == null)
{
lock (syncRoot)
{
if (uniqueInstance == null)
{
uniqueInstance = new SingletonDL();
}
}
}
return uniqueInstance;
}
}
class Singleton
{
private static readonly Singleton uniqueInstance = new Singleton();
private Singleton() { }
public static Singleton GetInstance()
{
return uniqueInstance;
}
}
#if LANGUAGE_JAVA
class SingletonMT
{
private static SingletonMT uniqueInstance;
private SingletonMT() {}
public static synchronized SingletonMT GetInstance() {
if (uniqueInstance == null) {
uniqueInstance = new SingletonMT();
}
return uniqueInstance;
}
}
class SingletonDL
{
private static SingletonDL uniqueInstance;
private SingletonDL() {}
public static SingletonDL GetInstance() {
if (uniqueInstance == null) {
synchronized (SingletonDL.class) {
if (uniqueInstance == null) {
uniqueInstance = new SingletonDL();
}
}
}
return uniqueInstance;
}
}
class Singleton
{
private static Singleton uniqueInstance = new Singleton();
private Singleton() {}
public static Singleton GetInstance() {
return uniqueInstance;
}
}
#endif
3、注意与全局变量、静态变量的区别