Avoiding static methods and variables in a Java Class file that handles config.properties

I am working on a simple Java application, and I created the Config.java class to handle application properties, thereby avoiding hard coding.

The Config.java class is not a static class, and I create an instance of the Config.java class in another Serial.java class.

The main method is in another class called App.java. So, I have 3 classes:

  • App.java
  • Serial.java (an instance of the Config class is here as a private variable)
  • Config.java

At this point, everything is in order, and there are no flaws in the design of OOP. However, I need to create another class in which I have to call methods from the Config.java class. What would be the best approach to have only one instance of the Config.java class :

  • Changing the methods of the Config.java class from public to static?
  • Creating recipients and setters for a Config instance that is in the Serial.java class?

Are there any other options / methods that I can use to achieve my goal.

Any help or suggestions are greatly appreciated.

+4
source share
2 answers


, Config Serial:

class Serial {
    private Config config = new Config();
}

, Serial, :

Config config = new Config();
Serial serial = new Serial(config);

Serial :

class Serial {
    private Config config;

    public Serial(Config config) {
        this.config = config;
    }
}

, Config:

OtherObj other = new OtherObj(config);

OtherObj :

class OtherObj {
    private Config config;

    public OtherObj(Config config) {
        this.config = config;
    }
}

.

+6

, :

  • getConfig App (, Config App) App .
  • ,
0

Source: https://habr.com/ru/post/1608710/


All Articles