Singleton Pattern
Singleton Pattern
// Private constructor to
// prevent external instantiation
class Singleton {
// Making the constructor as Private
private Singleton()
{
// Initialization code here
}
}
4.3. Static Factory Method:
A crucial aspect of the Singleton pattern is the presence of a static factory
method. This method acts as a gateway, providing a global point of access to the
Singleton object. When someone requests an instance, this method either creates
a new instance (if none exists) or returns the existing instance to the caller.
Screenshot-2023-12-07-174635
Implementation of Singleton Method Design Pattern
The implementation of the singleton Design pattern is very simple and consists
of a single class. To ensure that the singleton instance is unique, all the
singleton constructors should be made private. Global access is done through a
static method that can be globally accesed to a single instance as shown in the
code.
class GFG {
public static void main(String[] args)
{
Singleton.getInstance().doSomething();
}
}
Output
Singleton is Instantiated.
Somethong is Done.
The getInstance method, we check whether the instance is null. If the instance
is not null, it means the object was created before; otherwisewe create it using
the new operator.
Classic-Implementation
Let’s see various design options for implementing such a class. If you have a
good handle on static class variables and access modifiers this should not be a
difficult task.
Note: Singleton obj is not created until we need it and call the getInstance()
method. This is called lazy instantiation. The main problem with the above
method is that it is not thread-safe. Consider the following execution sequence.
This execution sequence creates two objects for the singleton. Therefore this
classic implementation is not thread-safe.
A better solution is to make the class itself responsible for keeping track of
its sole instance. The class can ensure that no other instance can be created
(by intercepting requests to create new objects), and it can provide a way to
access the instance. This is the Singleton pattern.