Background: I have some classes implementing a subject/observer design pattern that I've made thread-safe. A subject
will notify it's observers
by a simple method call observer->Notified( this )
if the observer
was constructed in the same thread as the notification is being made. But if the observer
was constructed in a different thread, then the notification will be posted onto a queue
to be processed later by the thread that constructed the observer
and then the simple method call can be made when the notification event is processed.
So… I have a map associating threads and queues which gets updated when threads and queues are constructed and destroyed. This map itself uses a mutex to protect multi-threaded access to it.
The map is a singleton.
I've been guilty of using singletons in the past because "there will be only one in this application", and believe me - I have paid my penance!
One part of me can't help thinking that there really will be only one queue/thread map in an application. The other voice says that singletons are not good and you should avoid them.
I like the idea of removing the singleton and being able to stub it for my unit tests. Trouble is, I'm having a hard time trying to think of a good alternative solution.
The "usual" solution which has worked in the past is to pass in a pointer to the object to use instead of referencing the singleton. I think that would be tricky in this case, since observers and subjects are 10-a-penny in my application and it would very awkward to have to pass a queue/thread map object into the constructor of every single observer.
What I appreciate is that I may well have only one map in my application, but it shouldn't be in the bowels of the subject and observer class code where that decision is made.
Maybe this is a valid singleton, but I'd also appreciate any ideas on how I could remove it.
Thanks.
PS. I have read http://stackoverflow.com/questions/1300655/whats-alternative-to-singleton and this article mentioned in the accepted answer. I can't help thinking that the ApplicationFactory it just yet another singleton by another name. I really don't see the advantage.