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?
Add parameter of the
Application
type to the constructors of the composites. When you create their instances just passthis
. For exampleChange the constructor of your
Application
class to beprivate
and send thethis
object to theApplicationXxx
classes.You will be able to call
new
on theApplication
class from within themain
method.Your
ApplicationSettings
,ApplicationModel
,ApplicationView
andApplicationController
must be updated to take anApplication
object in their constructors.I tried this right now, you can pass
this
as a constructor arg within the constructor ofApplication
to other classes (assuming the have a reference declared for the main class). That way you can obviously make multiple instances of theApplication
class. If that is what you want...You want to use the Singleton design pattern if you need to guarantee there will only be one instance of Application and you need it to be accessible by those classes. I'm not going to comment on if it's the best way to build your application, but it will satisfy the requirements in your question.
Singleton design pattern tutorial
I would use a singleton on Application class.
Put a
public static
method to return your one and only application instance.You can read more about singleton design pattern here.
Every time you need the one and only
Application
instance, you do: