假设我有一个这样的Java类:
public class ClassicSingleton {
private static ClassicSingleton instance = null;
protected ClassicSingleton() {
// Exists only to defeat instantiation.
}
public static ClassicSingleton getInstance() {
if(instance == null) {
instance = new ClassicSingleton();
}
return instance;
}
public void initialize(String id, Double num, String data){
....
}
}
如果我将在另一个类中访问它的“实例”,那么我的ClassicSingleton的理想方法类型是什么?
应该初始化一个静态函数,以便我可以在其他类中调用它:
ClassicSingleton mySingleton = ClassicSingleton.getInstance();
mySingleton = ClassicSingleton.initialize("id",0.0,"data");
还是应该保留Initialize并致电:
ClassicSingleton mySingleton = ClassicSingleton.getInstance();
mySingleton.initialize("id",0.0,"data");
最佳答案
如果要访问实例,请使用第二个选项
ClassicSingleton mySingleton = ClassicSingleton.getInstance();
mySingleton.initialize(“ id”,0.0,“ data”);