在Java中,getInstance()方法通常用于获取类的单例实例。为了优化getInstance()方法,我们可以采用以下几种策略:
public class Singleton {
private static Singleton instance;
private Singleton() {
// 防止反射攻击
if (instance != null) {
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public static synchronized Singleton getInstance() {
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 RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public static Singleton getInstance() {
return instance;
}
}
public class Singleton {
private static volatile Singleton instance;
private Singleton() {
// 防止反射攻击
if (instance != null) {
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
public static Singleton getInstance() {
if (instance == null) {
synchronized (Singleton.class) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton {
private Singleton() {
// 防止反射攻击
if (SingletonHolder.instance != null) {
throw new RuntimeException("Use getInstance() method to get the single instance of this class.");
}
}
private static class SingletonHolder {
private static final Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
public enum Singleton {
INSTANCE;
// 添加其他方法
public void someMethod() {
// ...
}
}
根据具体需求和场景,可以选择合适的优化策略。