Definition
Sorry about that whisky image. I, too, love click baits 😉
The singleton pattern is a software design pattern that restricts the instantiation of a class to one object. Singleton pattern is a convention for ensuring one and only one object is instantiated for a given class.
Usage
Places where only one object is needed.
Example:
- Threadpool
- Cache
- The object used for logging
At some places, if we were to instantiate more than one object, we would be having incorrect programming behavior, overuse of resource, or inconsistent results.
Implementation
To begin implementation, let’s set our objectives:
Objective: Ensure no other class can make a object of our singleton class
How do we ensure that? Remember, how we make a new class? Like this :
MyClass myClass = new MyClass();
But what if the public constructor of class MyClass is declared private. The above-mentioned declaration would not work because it can’t find a constructor to build an object.
public MyClass {
private MyClass() {}
}
But this constructor can certainly be called inside the method of MyClass like shown below:
public MyClass {
private MyClass() {}
public static MyClass getInstance(){
return new MyClass();
}
}
Now, any class outside MyClass can call this getInstance() method and can have a instance of MyClass. Only if we could return the same instance again and again when getInstance() is called, we would have fulfilled our objective.
We know that static variable have only one copy of each static variable per class, regardless of how many objects are created from it. Using this information, what if I attempt something like this :
public MyClass {
private MyClass() {}
private static MyClass instance;
public static MyClass getInstance(){
if(instance == null){
instance = new MyClass();
}
return instance
}
}
This works. But we have a small problem here. What if there are two threads which call getInstance() method at the same time and the instance variable is not initialized yet?
There will be two different objcets of MyClass would be returned. We have two approach to tackle this situation:
1. Move From Lazy Initialization to eagerly initialization
Something like this:
public MyClass {
private MyClass() {}
private static MyClass instance = new MyClass();;
public static MyClass getInstance(){
return instance
}
}
Downside of this approach, we will make one object even if we don’t need one.
2. Use Double Lock
public MyClass {
private MyClass() {}
private static MyClass instance;
public static MyClass getInstance(){
if(instance == null){
synchronized (MyClass.class){
instance = new MyClass();
}
}
return instance
}
}
Congratuations! Now, you have made MyClass a singelton class.
Further reading:
https://stackoverflow.com/questions/6109896/singleton-pattern-bill-pughs-solution
If you liked this article and would like one such blog to land in your inbox every week, consider subscribing to our newsletter:Â https://skillcaptain.substack.com
Leave a Reply