我使用以下代码创建了一个单例类:
public class Singleton {
private static Singleton instance = null;
private Singleton() {
// Exists only to defeat instantiation.
}
public static Singleton getInstance() {
if(instance == null) {
instance = new Singleton();
}
return instance;
}
}
我现在想使用这个单例类将我的程序中的数据提供给我的所有类(任何建议的修改都非常受欢迎)。我该如何处理?
答案 0 :(得分:1)
现在,您可以在构造函数中使用数据初始化Singleton,或者可以向Singleton类添加方法以获取数据。
然后你只需要在其他类中导入Singleton类并使用getInstance()获取你的实例。
如果您想了解一种从多个类访问数据的最新方法,您可以查看依赖注入。