单例模式
对于资源
java
package singleton;
public record Resource(String name) {
}
饿汉式
java
package singleton;
public final class HungrySingleton {
private static final Resource INSTANCE = new Resource("hungry");
public static Resource getInstance() {
return INSTANCE;
}
private HungrySingleton() {
}
}
懒汉式
java
package singleton;
public final class LazySingleton {
private static volatile Resource INSTANCE;
public static synchronized Resource getInstance() {
if (INSTANCE == null) {
INSTANCE = new Resource("lazy");
}
return INSTANCE;
}
public static Resource getInstanceV2() {
if (INSTANCE == null) {
synchronized (LazySingleton.class) {
if (INSTANCE == null) {
INSTANCE = new Resource("lazy v2");
}
}
}
return INSTANCE;
}
private LazySingleton() {
}
}
静态内部类(JVM 特性)
java
package singleton;
public final class InnerClassSingleton {
public static Resource getInstance() {
return InstanceHolder.INSTANCE;
}
private static class InstanceHolder {
private static final Resource INSTANCE = new Resource("inner class");
}
private InnerClassSingleton() {
}
}
枚举类(JVM 特性)
java
package singleton;
public enum EnumSingleton {
INSTANCE;
private final Resource resource;
EnumSingleton() {
this.resource = new Resource("enum");
}
public Resource getResource() {
return resource;
}
}