Design flaws of the singleton pattern

The paradigm

Consider this common singleton pattern implementation:

The problem is that you can inherit this class and create a public constructor if there is no private constructor. Furthermore, static members are allowed. This is no longer a singleton at all. Setting the class as sealed can be an acceptable solution, but you must implement singleton by singleton, i.e., more than ten lines. Thus, coding a such singleton can be the source of many errors and difficulties. Thinking with factoring is not only an agile principle, it is a mathematical theorem.

Defining a generic singleton

A generic solution is to check the absence of static members and that there is only one parameterless private constructor, or an exception is thrown. Singletons that inherit this class can't be inherited and must be sealed. Moreover, the implementation of singleton types are checked at program startup. Therefore, it is not the best solution, but the only thing to do is to create one parameterless private constructor, no static members, and seal the class.

  Generic Persistent Singleton Sample (53.4 KiB)

Continue reading »

Work in progress

The Ordisoftware™ project started in January 2004.