I am working on a simple Java Application and I've created a class called Config.java in order to handle the Application properties, thus, avoiding hard-coding.
The Config.java class is not a static class, and I am creating an instance of the Config.java class in another class called Serial.java.
The main method is located in another Class called App.java. So I have 3 Classes in total:
- App.java
- Serial.java (Instance of Config class is located here as a private variable)
- Config.java
At this stage, all is fine and there are no flaws within the OOP Design. 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 in order to have just one instance of the Config.java class:
- Changing the methods of the Config.java class from public to static?
- Creating getters and setters for the Config instance which is located in the Serial.java class?
Are there any more options/techniques I can use in order to reach my goal.
Any help or suggestions are highly appreciated.
Sounds like a job for dependency injection
It sounds like you're instantiating
Config
inSerial
:Instead of creating it in
Serial
, pass it in:The
Serial
class would look like:That way you can also pass it to the other object that must call methods from
Config
:With
OtherObj
defined as:This well help you avoid static.
Although it depends on details of your domain I see two viable alternatives: