饿汉式
在程序启动或单件模式类被加载的时候,单件模式实例就已经被创建,换句话说,不管你用的用不上,一开始就建立这个单例对象。
/**
* 饿汉模式
* @author zhou.ni
* @versionCode 1 <每次修改提交前+1>
*/
public class HungrySingle {
private static final HungrySingle sInstance = new HungrySingle();
private HungrySingle() {
}
public static HungrySingle getInstance() {
return sInstance;
}
}
在饿汉模式中,初始化变量的时候最好加上 final 关键字,这样比较严谨。
懒汉式
用synchronized 进行同步处理,并且双重判断是否为null,我们看到synchronized (Singleton.class)里面又进行了是否为null的判断,这是因为一个线程进入了该代码,如果另一个线程在等待,这时候前一个线程创建了一个实例出来完毕后,另一个线程获得锁进入该同步代码,实例已经存在,没必要再次创建,因此这个判断是否是null还是必须的。
但是带来了一个问题。那就是每次都要判断锁,程序的执行效率就会比较低。
/**
* 懒汉模式
* @author zhou.ni
* @versionCode 1 <每次修改提交前+1>
*/
public class LazySingle {
private static volatile LazySingle sInstance = null;
private LazySingle() {
}
public static LazySingle getInstance() {
if (sInstance == null) {
synchronized (LazySingle.class) {
if (sInstance == null) {
sInstance = new LazySingle();
}
}
}
return sInstance;
}
}
在懒汉模式中,初始化变量的时候加上 volatile 关键字
如何选择
如果单例模式实例在系统中经常会被用到,饿汉式是一个不错的选择。反之如果单例模式在系统中会很少用到或者几乎不会用到,那么懒汉式是一个不错的选择。
网友评论