Which design pattern should be used for global configuration

I read that using static variables in a class that has never been created is a bad idea, because variables can rotate to zero when the class is no longer in memory. Has the meaning.

This is what I did for an example.

public class MasterParameters {

public static boolean           DEBUG_MODE =                true;
protected MasterParameters(){
    // Exists only to defeat instantiation.
}

}

I also heard that using Singleton is equally bad, and people suggest using dependency injection. However, this seems complicated and redundant for what I need. Am I just not looking at the right examples?

I want an easy way to define a variable in one place that can be accessed from anywhere in my code without having to pass a parameter object. What do you suggest? Thank:)

+5
source share
2 answers

I would suggest the Singleton template (I know that many people don't like it), but it seems like this is the easiest solution. Take a look at this piece of code:

public enum Constants {
    INSTANCE;

    public void isInDebugMode() { 
        return true;
    }
}

Here's how you use it (even from static code):

if(Constants.INSTANCE.isInDebugMode()) {....}

You might also think of a more complex solution:

public enum Constants {
    DEBUG(true),
    PRINT_VARS(false);

    private boolean enabled;

    private Constants(boolean enabled) {
        this.enabled = enabled;
    }

    public boolean isEnabled() {
        return enabled;
    }
}

Usage example:

if(Constants.DEBUG.isEnabled()) {....}
+4
source

It is best to use a static method instead of a variable:

public class MasterParameters {

public static boolean DebugMode(){
     return true; // change this
}
protected MasterParameters(){
    // Exists only to defeat instantiation.
}
0
source

All Articles