单例模式主要是为了避免因为创建了多个实例造成资源的浪费,且多个实例由于多次调用容易导致结果出现错误,而使用单例模式能够保证整个应用中有且只有一个实例。
- 定义:
- 私有化该类的构造函数
- 通过new在本类中创建一个本类对象
- 定义一个公有的方法,将在该类中所创建的对象返回
- 属于创建型模式
- 非懒加载
- 线程安全
- 实现简单
public class Singleton {
private Singleton() {
}
private static Singleton instance = new Singleton();
public static Singleton getInstance() {
return instance;
}
}
懒汉式
线程不安全
- 懒加载
- 线程不安全
- 实现简单
public class Singleton {
private Singleton() {
}
private static Singleton instance;
public static Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
线程安全
- 懒加载
- 线程安全
- 实现简单
public class Singleton {
private Singleton() {
}
private static Singleton instance;
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 synchronized Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
登记式/静态内部类
- 懒加载
- 线程安全
public class Singleton {
private static class SingletonHolder{
private static final Singleton INSTANCE = new Singleton();
}
private Singleton(){}
public static Singleton getInstance(){
return SingletonHolder.INSTANCE;
}
}
枚举
- 非懒加载
- 线程安全
public enum SingletonEnum {
instance;
private SingletonEnum(){}
public void whateverMethod(){
}
// 使用
// SingletonEnum.instance.whateverMethod();
}



