Skip to content
BENIBIX Learn

Singleton Pattern

Development🏗️ ArchitectureDesign Patterns

Also known as Singleton

Only one object of a class may exist. Every part shares it.

Think of it like

Think of it like the one school bell. Every class hears the same bell, and there is never a second one.

Example

Jack's app reads its settings file once into a Config singleton. Every part asks Config for values. The file is never read twice.

Why it matters

Some things really should exist only once. The pattern stops two copies from drifting apart.

Definition

The singleton pattern makes sure a class has just one object. It also gives every part of the program a way to reach it. The first time it is asked for, the object is made. After that, the same object is handed back every time. It is often used for settings, a logger or a database connection pool. Many teams now avoid it, because it acts like a hidden global value.

Common mistake

Using singletons for all shared things. They make tests hard, since each test sees the same hidden object.

Key takeaways

  1. 1
    Only one. Never a second object.
  2. 2
    Reach it anywhere. One shared access point.
  3. 3
    Hidden global. Use with care.