February 12, 2005

Singleton - Pattern or Anti-Pattern?

It's interesting to see how various developers respond when you ask them about the singleton pattern. Most react positively, others say that it is an anti-pattern of the worst form.

Why it is considered an anti-pattern by some?
  1. In Java it doesn't always meet the contract of the 'Singleton Pattern' as defined in the GoF book. Classloaders mean that more than one instance of a Singleton can exist in the same JVM.
  2. Developers often use it as a dumping ground for de facto global variables, harking back to the most unstructured early days of programming.
  3. Implementations often feature 'Singleton' in the names of implementing classes and other code becomes dependent on the fact that it is an instance of the singleton pattern.

I believe however that there is nothing wrong with the singleton pattern, just in implementations of it.

One should think of the singleton pattern as an implementation pattern for the factory and pool patterns. Developers should be handed a factory or pool and told only that it will give them an instance of a particular class or interface on request. They shouldn't know that it is the same object instance each time.

This allows the developer of the pool or factory to make efficient use of available resource, if possible, but also allows the implementation to be changed if necessity dictates. By hiding the usage of singleton behind the pool or factory patterns, code fragility is avoided.

No comments: