Singletons rule

Keep on the object-oriented track with singletons

Q: I have seen singleton classes used in many places. My question: What is the advantage of using a singleton over a class with static methods?

A: Utilities

You may ask, what's the problem with a list of functions?

Simple. With a list of functions you no longer perform object-oriented programming. In fact, your work easily devolves into a classic procedural program. Suddenly, objects no longer represent the focus of your program. You begin to fall into a data-centric programming mode. That is, instead of sending messages to objects that encapsulate state and behavior, you begin to call functions that act on data. Utilities lead to a clear division between behavior and data that you should never allow in an object-oriented design.

That's not to say that you should never use utilities. Object-oriented utilities do exist. There are times that you might need to treat objects as data. For example, I recently wrote a set of utilities that convert Java objects into a CORBA equivalent. It is difficult to turn those methods into a class since they really have no state. I also didn't want to embed the conversion code into the Java classes either. However, it is easy to mess it all up.


Use singletons when you want only one instance of a certain class in your system at any given time. An example could be a class that provides load-balanced access to CORBA servers. You wouldn't want two such objects, since each would have to get references to the same servers. Grabbing redundant resources would be wasteful. It is better to centralize the server access inside one instance.

Learn more about this topic