Tôi đã hỏi về việc nhận cá thể lớp duy nhất từ một lớp khác gần đây.Các tham chiếu đối tượng khác nhau cho cùng một đối tượng (?)
(How to get specific instance of class from another class in Java?)
Vì vậy, tôi đang cố gắng để làm cho nó hoạt:
My 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);
}
}
My 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;
}
}
Vấn đề là main
phương thức trả về khác nhau tham chiếu đối tượng.
[email protected]
[email protected]
Có gì sai với mã của tôi?
Nó sử dụng một đơn và các hình thức khác của nhà nước toàn cầu, đó là những gì là sai với nó. –
Tại sao không sử dụng enums khi bạn cần Singletons.? –