
确保系统内某些类至多只有唯一一个实例。

// 为何final
class final Singleton extends Serializable {
// 一上来就实例化,eagerly;线程安全吗?
private static Singleton instance = new Singleton();
private Singleton() { }
public static Singleton getInstance() {
return instance;
}
// 这是什么方法,来自谁?
private Object readResolve() throws ObjectStreamException {
return instance;
}
}
class SingletonLazy {
// 延迟实例化
private static SingletonLazy instance = null;
private SingletonLazy() { }
// 多线程访问会怎样
public static SingletonLazy getInstance() {
if (instance == null)
instance = new SingletonLazy();
return instance;
}
}
class SingletonLazySafe {
// 延迟实例化
private static SingletonLazySafe instance = null;
// 有没有什么问题?
public static synchronized SingletonLazySafe getInstance() {
if (instance == null)
instance = new SingletonLazySafe();
return instance;
}
private SingletonLazySafe() { }
}
class SingletonDoubleCheck {
// 延迟实例化,volatile 的作用?
private static volatile SingletonDoubleCheck instance = null;
public static SingletonDoubleCheck getInstance() {
if (instance == null) {
synchronized(SingletonDoubleCheck.class) {
// 这一次检查的意义是?
if (instance == null)
instance = new SingletonDoubleCheck();
}
}
return instance;
}
private SingletonDoubleCheck() { }
}
class SingletonStaticInnerClass {
public static SingletonStaticInnerClass getInstance() {
return SingletonHolder.instance;
}
private static class SingletonHolder {
private static SingletonStaticInnerClass instance = new SingletonStaticInnerClass();
}
private SingletonStaticInnerClass() { }
}
enum SingletonInEnum {
INSTANCE;
public void doSomething() {
}
}
参考:
