Search code examples
javaglobal-variableslocaleglobalizationshare

How to share which Locale to use among all the classes in Java?


I decided my software needs to go international, so I made one of the classes prompt the user which locale to use. To the 7 other classes I added a parameter to take this info in. Now, somehow this doesn't feel right. It seems to complicate things.

It seems more natural to make the chosen Locale a 'global' variable, instead of adding a parameter to all 7 other classes to take this info in. (do you agree?)

So I took a look at what's suggested: to define a public class with the desired variables as static members of it.(for example here)

In this example however, the value to be shared between all classes is independent of the user input. I don't have a clue how to share a variable that has not been set yet. Is there anyone who wants to spend a few words on this for me?


Solution

  • Let's assume you want to create a GlobalSettings class. You can do the following.

    class GlobalSettings {
      private static Locale locale = Locale.US;
    
      public static Locale getLocale() {
        return locale;
      }
    
      public static void setLocale(Locale newValue) {
        locale = newValue;
      }
    }
    

    then, from anywhere, you can call GlobalSettings.getLocale(). You can be more sophisticated, for instance, having a single instance of GlobalSettings with a private field locale, and then you can easily mock or replace for unit tests.