我最近问过从另一个班级获取类的唯一实例.
(How to get specific instance of class from another class in Java?)
所以,我试图让它工作:
我的应用程序:
public class Application
{
// I will always have only one instance of Application
private static Application _application;
// Every instance of Application (one in my case) should have its own View
private View view;
// Constructor for new instance of Application
private Application()
{
view = new View();
}
// Getter for my unique instance of Application
public static Application getSharedApplication()
{
if (_application == null)
_application = new Application();
return _application;
}
// Main class
public static void main(String[] args)
{
// So I'm accessing my instance of Application
Application application1 = getSharedApplication();
// Here is object reference
System.out.println(application1);
// And now I'm accessing the same instance of Application through instance of View
Application application2 = application1.view.getApplication();
// Here is object reference
System.out.println(application2);
}
}
我的看法:
public class View
{
// I'm accessing my instance of Application again
public static Application application = Application.getSharedApplication();
// This method should return my unique instance of Application
public Application getApplication()
{
return application;
}
}
问题是main方法返回不同的对象引用.
Application@1430b5c
Application@c2a132
我的代码出了什么问题?
最佳答案
这是发生的事情:
>程序首先调用Application application1 = getSharedApplication();
>它反过来调用调用new Application()的静态方法 – 该调用需要加载View类,它是Application的成员.
>加载View类并初始化其静态成员并运行getSharedApplication(); (请注意,在此阶段,_application仍为null).这也创建了一个新的Application()
您现在有2个应用程序实例.
请注意,如果添加View v = new View();作为main的第一行,您只有一个Application实例(从View的静态变量中加载一次).当你仔细思考但不是很直观时,这是有道理的…