Singleton

Creational pattern

The Singleton design pattern receives this name because it can only have a single instance of a specific class for the entire application; this is achieved by preventing the creation of multiple instances of the same class, as it typically happens with the new operator, and imposing a private constructor and a static method to get that instance.

The objective of this pattern is to guarantee the creation of a single instance of a specific class and the existence of a global reference for the entire application.

Singleton design pattern structure.
Singleton design pattern structure.

These are the components included in this pattern:

  • Client: It's the component requesting an instance of the Singleton class.
  • Singleton: It's the class implementing the Singleton pattern, from which only one instance can exist during the entire life-cycle of the application.
Singleton pattern sequence diagram.
Singleton pattern sequence diagram.
  1. The client requests for an instance of the Singleton through the getInstancemethod.
  2. The Singleton checks if the instance has already been created, if not, a new instance will be created.
  3. Either the newly created instance or the already existing instance is returned.

Real-world example

By implementing the Singleton design pattern, we are going to create an application for managing the system settings from a sole central point. Therefore, when the application starts, the initial settings will be loaded up and stay available.

Discover how the Singleton design pattern can help us solve this problem.
Discover how the Singleton design pattern can help us solve this problem.

About this book

Introducción a los patrones de diseño

Todo lo que acabas de ver en este artículo es solo una pequeña parte del libro Introducción a los patrones de diseño, el libro más completo de patrones de diseño en español, abarcamos 25 patrones de diseño junto con 25 proyectos del mundo real. Olvídate de aprender patrones de diseño con los ejemplos típicos de Internet de cómo hacer una pizza, animales y figuras geométricas. te invito a que veas mi libro:

Ver libro
All rights reserved ©
Reactive programming
LinkedinYoutubeTwitterFacebook

© 2021, Copyright - Oscar Blancarte. All rights reserved.