Is using a singleton to represent a Publish-subscribe message system a bad design choice?
Background
Im thinking about writing a pubsub implementation (using the singleton pattern) to allow for easy decoupling in my application that's using an MVCish architecture.
I have used the wxPython gui toolkit along with pyPubSub (which uses the singleton pattern to implement its Publisher -see here-) in the past and have found it a simple and effective way to decouple the model from the view. Im looking for a simple way to achieve the same kind of functionality in a java swing based application without the need for a large third party framework which I don't feel is necessary or merited.
I am aware of Java's observer interface and observable class but these are a little basic for my needs. I need to have the ability to send messages and data with different topics -different topics will be handled differently and therefore should have different handlers/callbacks.
I have read numerous threads and blog posts on the "evilness" of singletons, and have concluded that ideally we should not use them but practically some times we have to.
For this application I don't see it as a problem.. I don't see any issues with dependencies.
Is there cleaner way to design this ?
Pseudo Implementation
If I were to build a simple implementation based on pyPubSub, broadcasting a message from my model would look something like this..
//broadcast a messge.. i dont care if anyone is listening..
Publisher.getInstance().sendMessage("topicName", messageObject)
We then write an inner class in the controller to handle messages
for which ever topicname its bound to using the Publishers
subscribe
method.
//inner class to handle message recieved for "topicname"
private Class myPubsubListener implements PubsubListener {
public messageHandler(Message message) {
//dostuff..
}
}
Then we bind an instance of the myPubsubListener class to the "topicname" in the controller
//setting up a listener for a particular "topicname"
//bind the myPubsubListener to the "topicname" so that it will handle all
//all message sent with this topic name
Publisher.getInstance().subscribe(new myPubsubListener(), "topicname");
Notes:
Planning to use weak references for the PubsubListeners so as not distrupt garbage collection...
Also there will be no dependancy on topic names.. if topic name has
not been subscribed to, simply no message will be sentA topicname does not have to exist for it to be subscribed to
The number of listeners that can be subscribed to a topicname is
unlimited