Step by Step Singleton Deign Pattern
Step:-1 Create class can't access by out side the with help of constructor (so avoid the creation of object )so as below
class DemoSingleton {
private DemoSingleton(){
}
}
Step :-2 Then quick question in mind how we get the object that class or use it . so create a class type variable of DemoSingleton type with private and static
class DemoSingleton{
private static DemoSingleton demosingleton;
private DemoSingleton(){
}
}
Step :-3 Then create method who will create and check object is not more then on copy.
class DemoSingleton {
private static DemoSingleton demosingleton;
private DemoSingleton(){
}
public static DemoSingleton getDemoSingleton(){
if(demosingleton== null){
demosingleton=new DemoSingleton();
}
return demosingleton;
}
}
Step:4 But it is not food full in case of multiple threading so we can modify some code
class DemoSingleton {
private static DemoSingleton demosingleton;
private DemoSingleton(){
}
public static DemoSingleton getDemoSingleton(){
synchronized (DemoSingleton.class) {
if (demoSingleton == null) {
if(demosingleton== null){
demosingleton=new DemoSingleton();
}
}
}
return demosingleton;
}
}