单例模式
概述
- 单例模式是指在内存中永远只有一个类的实例。
- 有利于节约内存和保证共享计算的结果正确,方便管理。
单例模式的形式
- 饿汉式单例:在获取单例对象之前对象已经创建完成。
- 懒汉式单例:在真正需要单例对象的时候才会创建对象。推迟一些高开销对象的初始化操作。
饿汉式单例写法
饿汉式(静态常量)
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}
饿汉式(静态代码块)
public class Singleton {
private static final Singleton INSTANCE;
static {
INSTANCE = new Singleton();
}
private Singleton() {
}
public static Singleton getInstance() {
return INSTANCE;
}
}
懒汉单例写法
懒汉式(线程不安全)
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;
}
}
懒汉式(双重检查模式,推荐)
双重检查的优点:线程安全,延迟加载,效率较高。
public class Singleton {
private volatile static Singleton INSTANCE;
private Singleton() {
}
public static Singleton getInstance() {
if (INSTANCE == null) {
synchronized (Singleton.class) {
if (INSTANCE == null) {
INSTANCE = new Singleton();
}
}
}
return INSTANCE;
}
}