Friends Let Friends Write Singletons September 8th, 2003
Norman Richards recently posted a piece called Friends don't let friends write singletons, in which he expresses contempt for the Singleton pattern. At the end of what I feel is a fairly unbalanced treatment, Norman concludes with "Avoiding singletons isn't always easy."
I'd go so far as to agree that the Singleton pattern is abused. But I suggest the reason Norman has noticed that it can be hard to avoid using the pattern, is that there are situations in which it makes a lot of sense.
Fortunately, he also said: "I want to again ask why one would ever use a singleton." I like a man who expresses willingness to be proven wrong. It's a trait I'm still cultivating. So this one goes out to Norman.
I have a user activity notification component for a J2EE application. It uses MDBs to service notification requests posted to a JMS Topic. The MDBs can send notification messages by email, in which case they're delivered via an SMTP connection pool. All well and good.
But I want runtime control of the size of the connection pool. I also want to be able to query the state of the MDBs and pause and restart them. I use JMX for this. The thing is, my JMX MBean needs to communicate with two things:
- The SMTP connection pool. This is facilitated by making the SMTP connection pool a singleton.
- The MDBs. This is facilitated by introducing an MDB Observer (see the Observer pattern), with which the MDBs register themselves as Subjects. The MDBs keep the Observer up to date with their status (for monitoring), and check with the Observer before doing certain kinds of work (for control).
Both of these solutions involve the Singleton pattern, and both would be a complete ball-ache to implement without it.
So just give me a second to get a decent grip on the baby, then you can do what you like with the bath water. :-)

