Singleton Class Code:
package designpattern.creational.singleton;
public class MySingleTon {
private MySingleTon() {
}
private static MySingleTon instance = null ;
public static synchronized MySingleTon getInstance() {
if(instance == null) {
System.out.println("Creating New Instance");
instance = new MySingleTon();
} else {
System.out.println("Returning Existing Instance");
}
return instance;
}
}
Code Explanation:
- Why the constructor declared private? – This is required so that the Singleton class could not be instantiated by any other class.
- Why the getInstance() method is synchronized? – This is required so that at any point of time only single class can access the Singleton Class. which means at any point of time we can have only single instance of class going outside the singleton class.
- Here we have created an static instance of MySingleTon Object, this object will be returned whenever user calls the Singleton class.
- Inside getInstance() we check whether the static instance of Singleton class holds the object if yes than we return the object else we create an new instance of the class.
- You must be wondering why clone method is written here. This is required so that we are not able to clone this class and create multiple instance of the SingleTon Class.
package designpattern.creational.singleton;
public class SingleTonClient {
public static void main(String[] args) {
//Will not compile, throw an error
MySingleTon s0 = new MySingleTon();
MySingleTon s0 = MySingleTon.getInstance();
System.out.println("Count:- " + s0.hashCode());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MySingleTon s1 = MySingleTon.getInstance();
System.out.println("Count:- " + s1.hashCode());
MySingleTon s2 = MySingleTon.getInstance();
System.out.println("Count:- " + s2.hashCode());
}
}
Here if you see if you try to create an new object of
MySingleTon class, the java compiler will give an error
that “Constructor MySingleton is not visible”. Then we
try to access the object of the Singleton class and to
cross check the hashcode printed is the same.
No comments:
Post a Comment