Singleton Design Pattern
Singleton Design Pattern
What is the Singleton Design Pattern in Java?
The Singleton Design Pattern ensures that a class has only one instance throughout the entire application and provides a global access point to that instance.
Key Goals:
- Only one object of the class exists.
- It is accessible from anywhere in the program.
- The instance is created only when needed (lazy loading - optional)
Why used?
- To avoid creating multiple heavy or conflicting objects.
- To maintain shared configuration or global resources.
How is Singleton Used in Java?
Singleton is commonly used for:
- Database connections
- Logging systems
- Configuration managers
- Thread pools
- Caching mechanisms
- File system managers
Usage steps:
- Make constructor private.
- Create a private static instance of the class.
- Provide a public static method to return that instance.
Real-World Example
Example: Logging System (Logger)
In real software, programs need a single logger to record messages.
If multiple logger objects were created:
- logs might conflict,
- files could become corrupted.
So, the Logger class becomes a Singleton — one shared instance writing to the log file.
Other real-world examples:
- Single Control Room in a company
- Single Print Spooler in an OS
- OS Task Manager instance

.png)
Comments
Post a Comment