Intent
- Ensure a class has only one instance, and provide a global point of access to it.
- Encapsulated "just-in-time initialization" or "initialization on first use".
Structure
Scheme of Singleton
代码:
// normal single ton, bad for multi-thread
public class SingleTon {
private static SingleTon instance;
private SingleTon() {
}
public SingleTon getInstance() {
if (instance == null) instance = new SingleTon();
return instance;
}
}
对于多线程的问题:
- 加synchronized关键字或加锁,但是性能可能下降100倍
// lock
public class SingleTon {
private static SingleTon instance;
Lock lock = new ReentrantLock();
private SingleTon() {
}
public SingleTon getInstance() {
lock.lock();
try {
if (instance == null) instance = new SingleTon();
return instance;
} finally {
lock.unlock();
}
}
}
- 使用"急切"创建实例,不用延迟创建(Recommanded)
// Initialization on Demand Holder
public class SingleTon {
private static SingleTon instance = new SingleTon();
private SingleTon() {
}
public SingleTon getInstance() {
return instance;
}
}
- 使用"双重检查枷锁",在getInstance()中减少使用同步
// double-checked locking
public class SingleTon {
private volatile static SingleTon instance = new SingleTon();
private SingleTon() {
}
public SingleTon getInstance() {
if (instance == null) {
synchronized (SingleTon.class) {
if (instance == null) instance = new SingleTon();
}
}
return instance;
}
}
Refenrence
- Design Patterns
- Head First 设计模式
网友评论