Wednesday, November 21, 2007

Singleton Anti-Pattern

The Singleton pattern is probably the most over used design pattern there is. Singletons are the same as global variables and make object collaboration less visible. They violate the Single Responsibility Principle mixing an object with its creation logic. They also create difficult to test code because they bind you to the exact type of the Singleton object and Singletons persist state causing test order to be dependent.

A Singleton object should be rarely used and when used it should be only used to solve a performance issue or as a last resort when parameter passing becomes very difficult.

1 comment:

Anonymous said...

Singletons do not necessarily bind to the exact type. A Singleton class can be implemented as a wrapper of a polymorphic type and in tests you can subsitute you real object with an object needed for testing.