CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 2 of 6 · 1 min read

What it is

A class with one instance and one way to reach it.

Think of the main water meter for a building. There is one. Every flat reads from the same one, and nobody installs a second to get a different answer.

GoF's intent is to make sure a class has only one instance, and to give a single global point of access to it. EJ describes a singleton as a class instantiated exactly once. It usually stands for a stateless object, such as a function, or for a part of the system that is truly unique.

GoF lists benefits. Access to the sole instance is controlled by the class itself. It is cleaner than a global variable, which would pollute the names visible everywhere. It can be subclassed. The number of instances can be changed later, since only the access method needs to change. And it is more flexible than a class full of static methods, which cannot be overridden.

Singleton

A singleton is a class that allows only one instance to exist, and offers one place to get it.

Example: a program-wide Config object.

Check yourself: 1. What two things does the GoF intent promise? 2. Why does GoF prefer a singleton to a global variable?