Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What design pattern should be used for a global configuration

I've been reading that using static variables in a class that's never instantiated is a bad idea, because the variables may turn null when the class is not longer in memory. Makes sense.

This is what I've been doing for an example

public class MasterParameters {

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

}

I've also heard using a Singleton is equally bad and people suggest using "dependency injection" -- This seems complicated and overkill for what I need, however. Am I just not looking at the right examples?

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

like image 561
Submerged Avatar asked Mar 06 '12 20:03

Submerged


People also ask

What is singleton and factory design pattern?

A singleton pattern ensures that you always get back the same instance of whatever type you are retrieving, whereas the factory pattern generally gives you a different instance of each type. The purpose of the singleton is where you want all calls to go through the same instance.

Which design pattern is best for Web application?

The Singleton Design Pattern That prevents multiple instances from being active at the same time which could cause weird bugs. Most of the time this gets implemented in the constructor. The goal of the singleton pattern is typically to regulate the global state of an application.

Which is the most used design pattern in Java?

Factory Design Pattern One of the most popular design patterns used by software developers is a factory method. It is a creational pattern that helps create an object without the user getting exposed to creational logic.


1 Answers

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

public enum Constants {
    INSTANCE;

    public void isInDebugMode() { 
        return true;
    }
}

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

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

You might also think about some more sophisticated solution:

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

    private boolean enabled;

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

    public boolean isEnabled() {
        return enabled;
    }
}

Example usage:

if(Constants.DEBUG.isEnabled()) {....}
like image 118
Sebastian Łaskawiec Avatar answered Sep 30 '22 21:09

Sebastian Łaskawiec