Java Singleton Considered Unsafe

Singleton is a design pattern intended to restrict the instantiation of a class to a guaranteed single instance.

The Singleton should, in fact be considered an Anti-Pattern, a pattern that should not be followed or used. It typically results from Cargo-Cult Programming programmers. The most common justification is to provide global accessed object this violates the very principle of Object Oriented Software of Encapsulation or isolation.

Violates Liskovs Substitution Principle as a consequence since a Singleton cannot be specialised (sub-typed) this means it typically aquires multiple addition responsibility violating the Single Responsibility Principle. ultimately becoming a God Object.

This introduce a global object rather than only in situations where a single object (Semaphore) is necessary.

Typical justifications are :

  • Target Object is expensive to instantiate.
    • Late (Lazy) Initialisation.
    • Early (Eager) Initialisation.

Typical Implementations are :

  • False, Bugged, no
  • Opaque.
  • Language Idioms.
  • Version of Language Idioms.
  • Problematic to debug.
  • Difficult or impossible to correctly specialise (Sub-Class).
  • Unsafe.
    • Violate the Single Responsibility Principle.
    • Violate the Rule of Demeter.

The Double Checked Locking Fiasco:

oo_java_singleton_unsafe.txt ยท Last modified: 2012/09/12 09:00 by Martin Spamer