What is Singleton pattern
[Wikipedia]: https://en.wikipedia.org/wiki/Singleton_pattern: In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to one “single” instance. This is useful when exactly one object is needed to coordinate actions across the system.
Characteristic
- only 1 instance create
- Guarantees controlled of a resource
- Lazily Loaded
Example of use
- Java Runtime (object)
- Logger
- Spring Beans
Code Example
java
1 | public class DbSingleton { |
Pitfalls
- Often overused, this could cause performance isue if make everything as singleton
- Difficult to unit test, as construstors and members are private
- If not carefull, the are not thread-safe. From above, we have added ensured thread safe
- Sometimes confuse for Factory: when people start making the getInstance method, as soon as it needs paramerters, it is not a singleton anymore but rather a factory.
- java.util.Calendar is NOT a singleton. It actually more of a prototype pattern. As you are getting a new unique instance each time you call getInstance method.








