Singleton design pattern is a Creational design pattern.It means create a single object or instance and make it global ,In other words, a class must ensure that only single object should be
created and single object can be used by all other classes.
There are two forms of singleton design pattern
Advantage of Singleton design pattern
To create the singleton class, we need to have static member of class, private constructor and static factory method.
public class Singletone {
private static Singletone obj; //lazy initialization
private Singletone() {
}
public static Singletone getSingletone() {
if (obj == null) {
obj = new Singletone();// instance will be created at request time
}
return obj;
}
public void doSomething() {
System.out.println("Singleton method called");
}
public static void main(String[] args) {
Singletone ex = Singletone.getSingletone();
ex.doSomething();
}
}
There are two forms of singleton design pattern
- Early Instantiation: creation of instance at load time.(private static A obj=new A();)
- Lazy Instantiation: creation of instance when required.(private static A obj; )
Advantage of Singleton design pattern
- Saves memory because object is not created at each request. Only single instance is reused again and again.
To create the singleton class, we need to have static member of class, private constructor and static factory method.
- Static member: It gets memory only once because of static, itcontains the instance of the Singleton class.
- Private constructor: It will prevent to instantiate the Singleton class from outside the class.
- Static factory method: This provides the global point of access to the Singleton object and returns the instance to the caller.
public class Singletone {
private static Singletone obj; //lazy initialization
private Singletone() {
}
public static Singletone getSingletone() {
if (obj == null) {
obj = new Singletone();// instance will be created at request time
}
return obj;
}
public void doSomething() {
System.out.println("Singleton method called");
}
public static void main(String[] args) {
Singletone ex = Singletone.getSingletone();
ex.doSomething();
}
}
Comments