Codacoda
Back to Academy

design patterns

Singleton

The Singleton pattern ensures a class has only one instance and provides a global point of access to it. It is useful when exactly one object is needed to coordinate actions across the system. The key participants are the Singleton class itself, which defines a static method (getInstance) that returns the same instance every time. Think of it like a government — a country has only one official government at a time, and that government provides a global point of access for citizens. Use Singleton when there must be exactly one instance of a class, such as a configuration manager, connection pool, or logging service, and it must be accessible from a well-known access point.

Use Cases

  • Database connection pool management
  • Application configuration/settings manager
  • Logging service shared across the application
  • Caching layer with a single shared cache instance

Visualization

getInstance()getInstance()Singleton-instance: Singleton+getInstance()-constructor()ClientAdoWork()ClientBdoWork()
Speed:1x
Singleton — ensures a class has only one instance with a global access pointStep 1 / 7

Implementation

Output

Click "Run Code" to see output...