一:什么是单利模式
单例:保证一个类仅有一个实例,并提供一个访问它的全局访问点。其目的是保证整个应用中只存在类的唯一个实例。
二:单利模式的四种实现方式
2.1:饿汉式
public class Singleton {
private static Singleton instance = new Singleton();
// 私有化构造方法
private Singleton() {
}
public static Singleton getInstance() {
return instance;
}
}
2.2:懒汉式
public class Singleton {
//volatile 关键字记得加
private static volatile Singleton instance;
private Singleton() {
//empty
}
public Singleton getInstance() {
if (null == instance) {
synchronized (Singleton.class) {
if (null == instance) {
instance = new Singleton();
}
}
}
return instance;
}
}
2.3:使用static的关键字来保证我们的单例
public class Singleton {
private Singleton() {
}
/**
* 推荐使用这方法
* 使用static的关键字来保证我们的单例
* static只在使用的时候才会初始化、且只初始化一次
*/
private static class InstanceHolder {
private final static Singleton instance = new Singleton();
}
private static Singleton getInstance() {
return InstanceHolder.instance;
}
}
2.4:使用枚举来实现单例
public class Singleton {
private Singleton() {
}
/**
* 枚举是线程安全的,且构造函数只会被装载一次
*/
private enum Singleton {
INSTANCE;
private final Singleton instance;
Singleton() {
instance = new Singleton();
}
public Singleton getInstance() {
return instance;
}
}
public static Singleton getInstance() {
return Singleton.INSTANCE.getInstance();
}
}
总结:推荐使用第三、四种方式,使用第二种方式的时候 volatile 关键字别忘记加。