单例模式
单例模式的目的是为了保证在一个进程中,某个类有且仅有一个实例。
保证一个类仅有一个实例,并提供一个访问它的全局访问点。
- 饿汉式(静态常量)
- 懒汉式(同步方法)
- 懒汉式(双重检查)
- 懒汉式(静态内部类)
- 枚举方式
饿汉式(静态常量)
// 饿汉式
// 类加载时就完成实例化,没有多线程下同步的问题;但没有懒加载/延迟加载效果
// 如果从未使用该实例,则会造成内存浪费
// 推荐使用
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
}
public static Singleton getInstance() {
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 static volatile Singleton instance;
private Singleton() {
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
懒汉式(静态内部类)
// 懒汉式(静态内部类)
// 外部类加载时,不会加载静态内部类,有延迟加载效果
// 类加载的时候,是线程安全的
// 综合:使用时才会实例化,有延迟加载效果;线程安全
// 推荐使用
public class Singleton {
private Singleton() {
}
private static class SingletonInstance {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return SingletonInstance.INSTANCE;
}
}
枚举方式
// 枚举方式
// 类加载的时候,是线程安全的
// 能防止反序列化创建新对象
// 能防止反射创建新对象
// 是不会被破坏的单例
// 推荐使用
public enum Singleton {
INSTANCE;
public void func() {
System.out.println("Singleton func");
}
}