在Java中,getInstance()
方法通常用于获取类的单例实例。替代方案取决于您希望如何实现单例模式。以下是两种常见的单例模式实现方法:
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// 防止反射攻击
if (instance != null) {
throw new IllegalStateException("Instance already created.");
}
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton {
private static final Singleton instance = new Singleton();
private Singleton() {
// 防止反射攻击
if (instance != null) {
throw new IllegalStateException("Instance already created.");
}
}
public static Singleton getInstance() {
return instance;
}
}
public enum Singleton {
INSTANCE;
// 添加您需要的属性和方法
public void someMethod() {
// ...
}
}
要使用枚举实现单例,您可以像这样调用getInstance()
方法:
Singleton singleton = Singleton.getInstance();
singleton.someMethod();