Junior
Where can the Singleton pattern be applied?
sobes.tech AI
Answer from AI
In scenarios where only one instance of a class is required throughout the system and this instance must be globally accessible.
Examples:
- Logging management: A single logger instance for centralized logging of application events.
public class Logger { private static Logger instance; private Logger() { // Private constructor to prevent external instantiation } public static Logger getInstance() { if (instance == null) { instance = new Logger(); } return instance; } public void log(String message) { System.out.println("LOG: " + message); } } - Application configuration: Access to configuration parameters from a single source.
- Thread pool: Managing a shared thread pool for executing tasks.
- Device drivers: If a device supports only one connection or driver instance.
- Factories: To create a single instance of a factory responsible for creating other objects.
- Cache management: Centralized cache data management.