在Java中,实现单例模式的方式主要有以下几种:
- 饿汉式(eager loading)
在类初始化时直接创建对象实例,线程安全。
## www.itzhimei.com 代码块
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
- 懒汉式(lazy loading)
类初始化时不创建实例,第一次使用时创建,线程不安全。
## www.itzhimei.com 代码块
public class Singleton {
private static Singleton instance;
private Singleton(){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
- 双重校验锁
懒汉式的线程安全版本,同步代码块保证多线程安全。
## www.itzhimei.com 代码块
public class Singleton {
private volatile static Singleton singleton;
private Singleton (){}
public static Singleton getSingleton() {
if (singleton == null) {
synchronized (Singleton.class) {
if (singleton == null) {
singleton = new Singleton();
}
}
}
return singleton;
}
}