在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();