Singleton Pattern

The Singleton pattern: guaranteeing a class has exactly one instance with a global access point, and why it is the most criticised of the 23.

  • 9 cards
  • 4 questions
  • About 15 min
  • Intermediate to Advanced
Share

Some things a program should have exactly one of: its configuration, its connection pool, its log. The Singleton pattern makes the class itself responsible for that, by creating its one instance on first request and handing the same object to every caller after.

This topic opens on that problem and the pattern's intent, then reads the parts of a singleton off the smallest class diagram in the catalogue. The template builds it in Python, Java and TypeScript, and adds the Java enum form that stays correct when several threads ask at once.

Two examples follow: an application configuration read from a file once, in Python, and the JDK's Runtime.getRuntime(). The comparison shows that a Python module is already created once and shared, so it is a singleton without a class. The gotcha is the reason Singleton is the most criticised of the 23 patterns: the one instance carries state from one test into the next. The exercise removes a singleton from a payment service while keeping one database connection.

By the end you can recognise a singleton, and say when one instance is right and when reaching it through a global is the problem.

Contents

9 cardsnot started