samedi 24 mars 2018

Class instance stored in static field - Java

1) what's the purpose of storing a class instance into a static variable (INSTANCE)

2) why do we have 2 cascade static methods main and start?

3) why o we do lazy init in controller()

thanks

code below is taken from Interactive Brokers ApiController

public class ApiDemo implements IConnectionHandler {

static {
    NewLookAndFeel.register();
}
public static ApiDemo INSTANCE;

private final IConnectionConfiguration m_connectionConfiguration;
private final JTextArea m_inLog = new JTextArea();
private final JTextArea m_outLog = new JTextArea();
private final Logger m_inLogger = new Logger(m_inLog);
private final Logger m_outLogger = new Logger(m_outLog);
private ApiController m_controller;
[...]

ILogger getInLogger() {
    return m_inLogger;
}

ILogger getOutLogger() {
    return m_outLogger;
}

public static void main(String[] args) {
    start(new ApiDemo(new DefaultConnectionConfiguration()));
}

public static void start(ApiDemo apiDemo) {
    INSTANCE = apiDemo;
    INSTANCE.run();
}

public ApiDemo(IConnectionConfiguration connectionConfig) {
    m_connectionConfiguration = connectionConfig;
    m_connectionPanel = new ConnectionPanel(); // must be done after connection config is set
}

public ApiController controller() {
    if (m_controller == null) {
        m_controller = new ApiController(this, getInLogger(), getOutLogger());
    }
    return m_controller;
}

private void run() {
    m_tabbedPanel.addTab("Connection", m_connectionPanel);
    m_tabbedPanel.addTab("Market Data", m_mktDataPanel);
[...]

}

Aucun commentaire:

Enregistrer un commentaire