Design pattern–单例模式
1)懒汉式,线程不安全
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2)懒汉式,线程安全
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
3)双重检验锁
private static volatile Singleton instance = null;
public static synchronized Singleton getInstance() {
if (instance == null) {
synchronised(Singleton.class) {
instance = new Singleton();
}
}
return instance;
}
4)饿汉式
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
5)静态内部类
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
6)枚举
public enum EasySingleton{
INSTANCE;
}