Wednesday 24 October 2018

Singleton Design Pattern in Java


  • singleton is a way to restrict only one object per a class  

    There are multiple ways of creating a singleton object 

 1) eager initialized singleton 

      public class MySingelton1 {

private final static  MySingelton1 myobj =new MySingelton1();
private MySingelton1() {
System.out.println("new instance created MySingelton1");
}

public static MySingelton1 getMyobj() {
return myobj;
}
}

This class object is created  only once during the loading time itself 

2) lazy initialized singleton
  
   public class MySingelton2 {
private  static volatile MySingelton2 myobj=null;
private MySingelton2() {
System.out.println("new instance created MySingelton2");
}

public static MySingelton2 getMyobj() {
 if (myobj == null) {
synchronized (MySingelton2.class)
{
if (myobj == null) {
myobj = new MySingelton2();
}
}
}

return myobj;
}
}
 This class object is cretaed only once when you called the getMyobj() method for the first time.


0 comments:

Post a Comment