我最近问过如何从另一个类中获取唯一的类实例。
所以,我试图让它工作:
我的Application
:
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);
}
}
我的View
:
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
我的代码有什么问题?