Lably
Skip to content

Singleton pattern

Programming technique to restrict a class to a single instance

  • 13 min read
  • 3 chapters

Related on Lably

Through Object-oriented programming, Class (programming) and Constructor (object-oriented programming)

More specifically, the singleton pattern allows classes to:

  • Ensure they only have one instance
  • Provide easy access to that instance
  • Control their instantiation (for example, hiding the constructors of a class)

The term comes from the mathematical concept of a singleton.

Common uses

Singletons are often preferred to global variables because they do not pollute the global namespace (or their containing namespace). Additionally, they permit lazy allocation and initialization, whereas global variables in many languages will always consume resources.

The singleton pattern can also be used as a basis for other design patterns, such as the abstract factory, factory method, builder and prototype patterns. Facade objects are also often singletons because only one facade object is required.

Logging is a common real-world use case for singletons, because all objects that wish to log messages require a uniform point of access and conceptually write to a single source.

Sign in to keep reading

2 more chapters are free with a Lably account.

More in Computing and communication