定义:确保一个类只有一个实例, 并提供一个全局访问点。
这个模式非常简单,下面给一个简单的代码说明
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (null == uniqueInstance) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
接下来我们考虑下单键模式下的同步与效率问题。如果有多个线程访问, 那需要确保同步, 我们可以把getInstance()方法改动如下:
public static synchronized Singleton getInstance() {
if (null == uniqueInstance) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
这样可以解决所线程同步问题, 但是同步性能会大大降低。 因为只有第一次执行此方法时才需要同步。我们利用双重检查加锁, 在getInstance 减少使用同步;
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (null == uniqueInstance) {
synchronized(Singleton.class) {
if (null == uniqueInstance) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
如果你关注性能, 那个这个方法可以帮你大大的减少getInstance的时间消耗。
参考:《Head First设计模式》