可以使用单例模式来避免使用静态方法创建具有相同值的实例。单例模式指一个类只能有一个实例,且该实例由该类自行创建并控制访问。
示例代码:
public class Singleton { private static Singleton instance;
private Singleton() {
// 私有构造函数
}
public static synchronized Singleton getInstance() {
if (instance == null) {
instance = new Singleton();
}
return instance;
}
}
在上述示例中,getInstance() 方法会检查实例是否为 null,如果是,则创建一个新的实例并返回;如果不是,则直接返回现有的实例。由于该方法是同步的,因此可以保证在多线程环境下仅创建一个实例。这样就可以避免使用静态方法创建具有相同值的实例。