1.什么是Java单例
Java单例是确保某个类只有一个实例,自行实例化并向整个系统提供这个实例。
优势:节约资源、避免重复创建对象。
缺点:多线程环境下需要处理线程安全及同步问题。
2.创建Java单例
(1)饿汉式(线程安全)
public class Singleton {
private static final Singleton INSTANCE = new Singleton();
private Singleton() {}
public static Singleton getInstance() {
return INSTANCE;
}
}
(2)懒汉式(双重检查)
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;
}
}
(3)静态内部类(线程安全)
public class Singleton {
private Singleton() {}
private static class Holder {
private static final Singleton INSTANCE = new Singleton();
}
public static Singleton getInstance() {
return Holder.INSTANCE;
}
}