单例模式:确保某一个类只有一个实例,而且自行实例化并向整个系统提供这个实例,这个类称之为单例类,它提供全局访问的方法。单例模式是一种对象创建型模式
1.饿汉式单例
class EagerSingleton {
private static final EagerSingleton instance = new EagerSingleton();
private EagerSingleton() { }
public static EagerSingleton getInstance() {
return instance;
}
}
1.懒汉式单例
class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton() { }
synchronized public static LazySingleton getInstance() {
if ( instance == null) {
instance = new LazySingleton();
}
return instance;
}
}
优化方案:
class LazySingleton {
private volatile static LazySingleton instance =null;
private LazySingleton() { }
public static LazySingleton getInstance() {
//第一重判断
if(instance == null) {
//锁定代码块
synchronized(LazySingleton.class) {
//第二重判断
if(instance == null) {
instance = new LazySingleton()
}
}
}
return instance;
}
}