singleton_code_demo

SingleTon basic logic

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class SingleTonClass {
private static SingleTonClass obj = null;
private SingleTonClass(){
/*Private Constructor will prevent
* the instantiation of this class directly*/
}

public static SingleTonClass objectCreationMethod(){
/*This logic will ensure that no more than
* one object can be created at a time */
if(obj==null){
obj= new SingleTonClass();
}
return obj;
}
public void display(){
System.out.println("Singleton class Example");
}
public static void main(String args[]){
//Object cannot be created directly due to private constructor
//This way it is forced to create object via our method where
//we have logic for only one object creation
SingleTonClass myobject= SingleTonClass.objectCreationMethod();
myobject.display();
}
}