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

我是研究僧i 提交于 2019-12-05 08:47:44

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

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

Change the constructor of your Application class to be private and send the this object to the ApplicationXxx classes.

private Application()
{
    settings        = new ApplicationSettings(this);
    model           = new ApplicationModel(this);
    view            = new ApplicationView(this, model);
    controller      = new ApplicationController(this);
}

You will be able to call new on the Application class from within the main method.

Your ApplicationSettings, ApplicationModel, ApplicationView and ApplicationController must be updated to take an Application object in their constructors.

Add parameter of the Application type to the constructors of the composites. When you create their instances just pass this. For example

public class Application {
  String s = "Setting";
  class ApplicationSettings {
    Application sc;
    ApplicationSettings(Application sc){
      this.sc = sc;
      System.out.println(sc.s);
    }
  }

  // Variables

  private ApplicationSettings settings;

  // Constructor

  public Application()
  {
    settings = new ApplicationSettings(this);
  }

  // Main method

  public static void main(String[] args)
  {
    Application application = new Application();

  }

  // Getters for settings, model, view, controller for instance of Application

}

I tried this right now, you can pass this as a constructor arg within the constructor of Application to other classes (assuming the have a reference declared for the main class). That way you can obviously make multiple instances of the Application class. If that is what you want...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!