```
单例模式 >>> 对象创建模式 >>> 确保一个类只有一个实例
```
```
只有一个实例、类内部创建唯一实例、对外提供该唯一实例
```
```
// ①懒汉式,线程不安全
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
```
```
// ②懒汉式,线程安全
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
// 线程安全、但并不高效、同一时刻只能有一个线程访问该方法、同步操作只需要在第一次调用创建对象时才被需要、获取对象时并不需要同步
```
```
// ③双重检验锁
// 双重检验锁模式(double checked locking pattern),是一种使用同步块加锁的方法
public class Singleton {
private static Singleton instance;
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) { //Single Checked
synchronized (Singleton.class) {
if (instance == null) { //Double Checked
instance = new Singleton(); // 并非是一个原子操、jvm存在指令重排序的优化作、分配内存、初始化、指向内存空间、
}
}
}
return instance ;
}
}
```
```
// ③双重检验锁 优化 volatile
public class Singleton {
private volatile static Singleton instance; //声明成 volatile
private Singleton (){}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
```
```
// ④饿汉式 static final field
public class Singleton {
// 在装载类的时候就创建对象实例
private static final Singleton instance=new Singleton();
private Singleton (){}
public static Singleton getInstance() {
return instance;
}
}
// 非惰性加载模式、无法在实例的创建依赖参数或者配置文件的时候使用、在 getInstance() 之前必须调用某个方法设置参数给它,那样这种单例写法就无法使用了
```
```
// ⑤静态内部类 static nested class
// 这种方法也是《Effective Java》上所推荐的
public class Singleton {
private static class SingletonHolder {
private static final Singleton INSTANCE = new Singleton();
}
private Singleton (){}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
```
```
// ⑥枚举 Enum
public enum Singleton{
INSTANCE;
}
```