单例模式必知必会
常见两种单例模式
/**
* <p>
* 饿汉单例模式,初始化时加载
* </p>
*/
public class EagerSingleton {
private static final EagerSingleton instance = new EagerSingleton();
private EagerSingleton() {
}
public static EagerSingleton getInstance() {
return instance;
}
}
/**
* <p>
* 懒汉模式,延迟加载,节省资源注意线程安全问题
* </p>
*/
public class LazySingleton {
private static LazySingleton instance = null;
private LazySingleton() {
}
synchronized public static LazySingleton getInstance() {
if (instance == null) {
instance = new LazySingleton();
}
return instance;
}
}/**
* <p>
* (加锁)懒汉模式,延迟加载,节省资源注意线程安全问题
* </p>
*/
public class SynLazySingleton {
private static SynLazySingleton instance = null;
private SynLazySingleton() {
}
public static SynLazySingleton getInstance() {
if (instance == null) {
synchronized (SynLazySingleton.class) {
instance = new SynLazySingleton();
}
}
return instance;
}
}
升级单利模式
/**
* <p>
* (双重锁)懒汉模式,延迟加载,节省资源,解决了线程安全问题,高频访问性能较低
* </p>
*/
public class DoubleSynSingleton {
private volatile static DoubleSynSingleton instance = null;
private DoubleSynSingleton() {
}
public static DoubleSynSingleton getInstance() {
if (instance == null) {
synchronized (DoubleSynSingleton.class) {
if (instance == null) {
instance = new DoubleSynSingleton();
}
}
}
return instance;
}
}
/**
* <p>
* 懒汉模式,延迟加载,节省资源,不存在线程安全问题(使用静态内部类)
* </p>
*/
public class IODHSingleton {
private IODHSingleton() {
}
private static class HolderClass {
private static final IODHSingleton instance = new IODHSingleton();
}
public static IODHSingleton getInstance() {
return HolderClass.instance;
}
}