Alternative to Singleton Template for Application Settings Manager

I have read all the reasons why singletones cause code problems, but I cannot find an alternative in the following scenario.

I have a Java Swing application. The user can set parameters through a graphical interface that affects both the display and the functionality of the application, and these parameters are saved and retrieved from the XML configuration file. When the application loads, a SettingsManager object is created. In the constructor, the settings manager parses the XML configuration file and saves all the settings locally for quick access (I will call it a cache). When a parameter is changed in the application, the parameter is immediately written to the file, but the cache is updated at the same time.

Problem

If multiple instances of the settings manager are created when one parameter is changed in one instance, the cache of the others becomes obsolete. Without using singleton, one possible way to fix this would be to not use the cache and simply always extract the settings from the file. This is not a terrible idea, but it is not preferable. If I did this, I would think that I would have to add extra work to make it thread safe.

Why Singleton Helps

If the ConfigurationManager is Singleton, there is only one cache, so it can never be deprecated. However, I can already see that this is not a good idea, since now it is a global variable, and classes that do not need access parameters can now access them. And from what I read, there were many other problems.

So, is there another way to create this that solves the problem without using Singleton?

+4
source share
2 answers

You can implement it so that the Settings control file is managed as a Singleton inside the class (this class will obviously not be single), and this class instance will be introduced only into those classes that need it. The grip handle (AKA bridge) will work well.

This will give you the best of both:

  • The settings manager is created only once and its cache. And the cache will never be obsolete.
  • Only those objects that need it will have access to it.

Obviously, this handle-body class (or any other solution) could be created anywhere bypassing dependency injection. Therefore, I’m not sure that an ideal solution to this problem exists, but it can take you a few steps closer.

0
source

Let me answer Brady's answer and suggest that the body-descriptor class method be declared protected . This would limit its availability. Another way is to put the class in a package containing the name "internal" (for example, com.mycorp.abc.internal). This may not restrict access, but it sends clear messages to other developers that the class / method should not really be used.

0
source

All Articles