单例模式
2018-01-22 本文已影响3人
倾倒的吞天壶
- 饿汉模式
public class Singleton {
//不使用也会实例化, 比较浪费资源
private static Singleton sInstance = new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return sInstance;
}
}
- 懒汉模式
public class Singleton {
private static Singleton sInstance = null;
private Singleton (){}
//使用时才会实例化, 但是每次都会同步, 造成不必要的同步浪费
public static synchronized Singleton getInstance() {
if (sInstance == null) {
sInstance = new Singleton();
}
return sInstance;
}
}
- Double Check Lock
public class Singleton {
//加入volatile关键字, 避免DCL失效问题
private volatile static Singleton sInstance = null;
private Singleton (){}
public static Singleton getInstance() {
if (sInstance == null) {
synchronized (Singleton.class) {
if (sInstance == null) {
sInstance = new Singleton();
}
}
}
return sInstance;
}
}
- 静态内部类
//比较完美的写法, 但是会有反序列化失效问题
public class Singleton {
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
}
- 枚举类
//避免了上述方法反序列看化时产生新的对象
public enum Singleton {
INSTANCE;
public void doMethod() {
}
}
//使用方法
Singleton s = Singleton.INSTANCE;
s.doMethod();