一.单件模式一般实现
二.单件模式多线程实现
一.单件模式一般实现
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
二.单件模式多线程实现
public class Singleton {
private static Singleton uniqueInstance;
private Singleton() {}
public synchronized static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
问题:性能降低
A. 如何getInstance()的性能对应用程序不是关键,就什么都不要做.同步可能使应用程序的执行效率降低100倍,但如果此方法不是被频繁的调用,则不用修改.因为同步的getInstance()方法既简单又有效.
B.使用"急切"创建实例,而不用延迟化的实例的方法
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
public synchronized Singleton getInstance() {
return uniqueInstance;
}
}
C.使用"双重检查加锁",尽量减少使用同步:如果性能是你关心的,此方法可大大减少时间消耗
public class Singleton {
private static volatile Singleton uniqueInstance;
public static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}