Avoiding static methods and variables in a Java Cl

2019-06-24 05:42发布

问题:

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:

  1. Changing the methods of the Config.java class from public to static?
  2. 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.

回答1:

Sounds like a job for dependency injection


It sounds like you're instantiating Config in Serial:

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

Instead of creating it in Serial, pass it in:

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

The Serial class would look like:

class Serial {
    private Config config;

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

That way you can also pass it to the other object that must call methods from Config:

OtherObj other = new OtherObj(config);

With OtherObj defined as:

class OtherObj {
    private Config config;

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

This well help you avoid static.



回答2:

Although it depends on details of your domain I see two viable alternatives:

  • Add a getConfig method to you App Class (considering that the Config belongs to the App) and using the App instance as a parameter to instantiate object of your new class.
  • Go for a singleton, which has many criticisms