单间模式是工作中遇到的比较多的一种模式,也叫单例模式。
单间模式确保一个类只有一个实例,并提供一个全局访问点。
创建单例模式主要有四种方法:
(1)第一种要介绍的方法,也是我在工作中用的最多的方法,看过Head First后就了解此方法的最大缺点。
public class Singleton {
private static Singleton uniqueInstance;
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
此方法在单线程中使用时没有问题,也存在效率问题,但是现在的应用基本都是多线程,当在多线程中使用时就可能导致创建两个实例。
(2)第二种方法是在getInstance方法前面加上同步synchronized关键字。
public class Singleton {
private static Singleton uniqueInstance;
//加上synchronized关键字
public synchronized static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}
此方法的最大弊端很显然是同步关键字引起的性能问题,同步一个方法可能造成程序执行效率下降100倍。如果应用可以接受同步方法带来额外负担,就可以使用此方法。
(3)第三种方法使用“急切“创建实例,而不用延迟实例化的做法,即在定义静态变量的时候来创建单间。
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
public synchronized static Singleton getInstance() {
return uniqueInstance;
}
}
如果使用单例是,在创建或者运行时的负担不太繁重时,可以使用。另外在创建时做一些初始化工作,而且也要传入一些参数时,这种方法就有可能不能满足需求。
(4)第四种方法是使用”双重检查加锁“,在getInstance中减少同步的使用。
public class Singleton {
// 使用了volatile关键字
private static volatile Singleton uniqueInstance;
public synchronized static Singleton getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
从代码中可以可以看到,只有第一次需要同步,这个方法大大的减少了getInstance的时间耗费。