I've created the following class with the main
method, which creates new instance of Application
and instances of ApplicationModel
, ApplicationView
and ApplicationController
for this particular Application
.
public class Application
{
// Variables
private ApplicationSettings settings;
private ApplicationModel model;
private ApplicationView view;
private ApplicationController controller;
// Constructor
public Application()
{
settings = new ApplicationSettings();
model = new ApplicationModel();
view = new ApplicationView(model);
controller = new ApplicationController();
}
// Main method
public static void main(String[] args)
{
Application application = new Application();
}
// Getters for settings, model, view, controller for instance of Application
}
I know, that there will always be only one unique instance of Application
.
And I want to get this particular instance in my ApplicationModel
, ApplicationView
and ApplicationController
classes.
How is it possible?
The instanceof operator in Java is used to check whether an object is an instance of a particular class or not. objectName instanceOf className; Here, if objectName is an instance of className , the operator returns true . Otherwise, it returns false .
You can do this: var mainSingleton = singleton<main>. instance; and it will always return the same instance of main .
Yes, that is of course possible. And it is easy to think about something where it is required. You might have a container which contains childs where the childs need a reference to the parent.
I would use a singleton on Application class.
Put a public static
method to return your one and only application instance.
public class Application
{
private Application() { } // make your constructor private, so the only war
// to access "application" is through singleton pattern
private static Application _app;
public static Application getSharedApplication()
{
if (_app == null)
_app = new Application();
return _app;
}
}
You can read more about singleton design pattern here.
Every time you need the one and only Application
instance, you do:
Application app = Application.getSharedApplication();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With