什么是单例模式?
保证一个类在内存中只存在一个对象,并且只提供一个对外访问对象的方式。
单例模式的几种实现方式
1、懒汉模式
Lazy 初始化:是
程安全:是
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
2、懒汉模式 -- 双重校验锁
Lazy 初始化:是
程安全:是
延迟加载,只有在真正使用的时候,才实例化
public class Singleton {
// volatile防止指令重排
private volatile static Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
//double check
if (instance == null) {
//加锁优化
synchronized (Singleton.