Card 09/ 09

RecapDifficulty: Advanced1 min

Recap: Singleton Pattern

One instance is often right; reaching it through a global is usually not.

Singleton makes a class create one instance of itself and hand it to every caller, which keeps one shared resource and, with it, one shared state.

  • Intent. Ensure a class has only one instance, and provide a global point of access to it.
  • Parts. A private constructor, a static field holding the instance, and a static method that creates it on first use and returns it.
  • Recognise it by shape. A class that keeps its one instance itself and hands it out through a static method such as getInstance().
  • In Java. The lazy form is unsafe with threads; an enum with one constant is created once by the JVM. Runtime.getRuntime() is the JDK's example.
  • In Python. A module is created once and shared by every import, which makes it a singleton without a class.
  • The cost. The global access point hides dependencies and carries state between tests. Create one instance and pass it in instead.