|
| 1 | +package src.main.java.com.designpatterns.singletonpattern; |
| 2 | + |
| 3 | +/** |
| 4 | + * The singleton pattern is a design pattern that restricts the instantiation of a class to one "single" instance. |
| 5 | + * This is useful when exactly one object is needed to coordinate actions across the system. The term comes from the |
| 6 | + * mathematical concept of a singleton. |
| 7 | + * <p> |
| 8 | + * The key idea in this pattern is to make the class itself responsible for controlling its instantiation (only once). |
| 9 | + * The hidden constructor (declared private) ensures that the class can never be instantiated from outside the class. |
| 10 | + * The public static operation can be accessed easily by using the class name and function name(Singleton.getInstance()) |
| 11 | + * |
| 12 | + * @see <a href="https://en.wikipedia.org/wiki/Singleton_pattern">Singleton Pattern</a> |
| 13 | + */ |
| 14 | +public class Singleton { |
| 15 | + private volatile static Singleton instance = null; |
| 16 | + |
| 17 | + private Singleton() { |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * A singleton implementation may use lazy initialization, where the instance is created when the static method |
| 22 | + * is first invoked. |
| 23 | + * <p> |
| 24 | + * If the static method might be called from multiple threads simultaneously, measures may need |
| 25 | + * to be taken to prevent race conditions that could result in the creation of multiple instances of the class. |
| 26 | + * <p> |
| 27 | + * The following implementation is a thread-safe sample implementation, using lazy initialization with |
| 28 | + * double-checked locking. |
| 29 | + * |
| 30 | + * @return the single instance of the Singleton class |
| 31 | + */ |
| 32 | + public static Singleton getInstance() { |
| 33 | + if (instance == null) { |
| 34 | + // First attempt to make thread safe |
| 35 | + synchronized (Singleton.class) { |
| 36 | + // Double Checked locking as multiple threads can reach the above step |
| 37 | + if (instance == null) { |
| 38 | + instance = new Singleton(); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + return instance; |
| 43 | + } |
| 44 | +} |
0 commit comments