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 libroSingleton
Creational patternThe 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.
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.
- The client requests for an instance of the Singleton through the getInstancemethod.
- The Singleton checks if the instance has already been created, if not, a new instance will be created.
- 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.