Singleton pattern only allows for one instance of the class to be created and exist in JVM.
- Gof Creational Pattern
- Only one instance of class
- Must have global access point to create the instance
- Singleton pattern is used for logging, drivers objects and caching and thread pool.
Singleton pattern could be implemented in different ways but must have the following:
1. private constructor to restrict instantiation of the class from other classes.
2. private static variable of the same class that is the only instance of the class
3. public static class that returns the instance of the class.
1. Eager initialization
instance is created at the time of class loading, easiest to code but has many drawbacks.
- instance is created regardless w/o considering the possibility of not using the class.
- doesnt provide any exception handling
2. Static block intialization
similar to eager initialization, but adds static when creating instance for exception handling. Eager intialization and Static block intialization instances are created when class is being loaded so it is not the best method to create a singleton pattern.
3. Lazy Initialization
Creates instance inside the global access method. It works fine in single-threaded environment but when working with multiple threads, if both threads are created at the same time, the singleton pattern will not working causing it to create two different instances of the class.
4. Thread Safe Singleton
applying synchronized to a global access method will allow thread wait for other working threads when using the method. But applying synchronized directly to the method will cause unnecessary time costs so for this, we can add a synchronized block inside another if statement, a double checked locking principle.
5. Bill Pugh Singleton Implementation
Bill Pugh created a pattern where using inner static helper class to create a thread safe singleton instance.
SingletonHelper class is not loaded into the memory until getInstance is called, which saves unnecessary memory costs. This is most widely used singleton pattern.
source: https://www.journaldev.com/1827/java-design-patterns-example-tutorial#creational-patterns
'IT > 디자인 패턴' 카테고리의 다른 글
Strategy Pattern (0) | 2020.02.28 |
---|---|
Builder Design Pattern (0) | 2020.02.25 |
Abstract Factory Design Pattern (0) | 2020.02.24 |
Factory Design Pattern (0) | 2020.02.22 |