javaoopmodel-view-controllerclassinstance

How to get specific instance of class from another class in Java?


I've created the following class with the main method, which creates a 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?


Solution

  • 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();