Singleton Pattern
1 min readSep 2, 2020
2. Part
In the last post, we started with Memento now let’s move on with a creational pattern called Singleton.
By using Singleton pattern you ensure instantiating your object to be strictly controlled. The Client can access the singleton instance through Singleton’s Instance operation.
Benefits:
- Controlled access to the sole instance.
- Reduced namespace
- Permits refinement of operations and representation.
- Permits a variable number of instances. The pattern makes it easy to change your mind and allow more than one instance
Cons:
- Increase dependencies
- Testing gets harder because the test cases most probably will have dependencies.
There are lots of implementation style for the Singleton pattern, I will use the so-called lazy implementation in java.
public class Singleton {
private static Singleton instance;
/**
* private constructor, no direct access
*/
private Singleton(){ }
/**
* used synchronized key word to make thread safe
* @return instantiate singleton instance
*/
public synchronized static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
The Singleton pattern is straightforward and easy to implement. Creating a Singleton instance is only possible via invoking the getInstance method.