Recently, I refactor code of my project, I found there are lots of singleton object, almost one function one singleton.
For example, I should do period task, so I have a class called CPeriodTask, and have a thread function called ScanPeriodTaskThreadProc and a member variable which save tasks, and CPeriodTask is a singleton object.
There are so many singleton object in my project, and a few of singleton object refer to
other singleton object.
Now I want to reduce use of singleton and break reference of singleton.
Any Suggestions, Thanks.
One way to reduce singletons is to create some god-class, a
SingletonManager, which can then contain all of the other singletons as instance members. That is, you remove the singleton behavior of the existing singletons in your projects, and this manager then creates/destroys these objects as desired, in the correct order, since you mentioned some of these objects have dependencies on each other.So at the top of main, you create the SingletonManager, publish some reference to this object so the rest of your code can get at these former-singleton objects. And, just as important, at the bottom of main, you “shutdown” the manager which itself then deterministically destroys these objects in the correct order. Again, this is important because you mentioned inter-dependencies between these objects, and at least one singleton you have now involves a thread.