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?
source share