Wednesday, 2 December 2015

Why Singleton Design Pattern is required?

Scenario :
If you have 3 classes consider ClassA,ClassB and ClassC.

ClassA has contain one method called displayMsg() method .

If you want to access the displayMsg() in ClassA from ClassB and ClassC.

you need to create ClassA object in ClassB and ClassC using the below command

ClassA objA=new ClassA();       

Once object of ClassA is created displayMsg()can be accessible from ClassB and ClassC


Example :

File 1: ClassA.java
 

package com.awf.org;

public class ClassA{
public void displayMsg(){


System.out.println("Class A method is called");
 

}
}


File 2: ClassB.java

package com.awf.org;

public class ClassB{
public static void main(String args[]){


ClassA objA=new ClassA();
objA.displayMsg();
 

}
}

File 3 :ClassC.java
package com.awf.org;

public class ClassC{


public static void main(String args[]){


ClassA objA=new ClassA();
objA.displayMsg();
 

}
}



Output :

If you ClassB  or ClassC you will get the below output

Class A method is called

Problem with the above code :

 If you have n number of Classes let us consider ClassB,ClassC........ClassN . Each Class need to access ClassA method displayMsg().

You used to create object in all Classes by using 

 

 ClassA objA=new ClassA();

 If you do this your heap memory will get full sometimes you will get java.lang.OutOfMemoryError

The java.lang.OutOfMemoryError: Java heap space error will be triggered when the application attempts to add more data(Object) into the heap space area, but there is not enough space for it.
Note :
There might be plenty of physical memory available, but the Java heap space error is thrown whenever the JVM reaches the heap size limit java.lang.OutOfMemoryError 

 
 To avoid the above problem use Singleton design pattern it will create only one object for particular class. That object can be useb by any class.


Example to create Singleton Class:


package com.awf.org;

public class MySingleton
{
    private volatile static MySingleton instance;
     
    private MySingleton()
    {
      
    }
   
     public static MySingleton getInstance()
    {
        if (instance == null) {
            synchronized (MySingleton.class) {
                if (instance == null) {              //
Doublecheck to avoid race condition
                    instance = new MySingleton();
                }
            }
        }
        return instance;

    }
   
    
}



The above class first check whether the instance for particular Class is already there or not . If it is there it will return existing object else it will create new object and it will return. Its used to avoid java.lang.OutOfMemoryError 


Now I will include Singleton Concept for our example . Just add our ClassA in singleton class this is the first way ,Second way you can make ClassA as Singleton class.


First Way : 

 Include ClassA in above Singleton Object .
If you to get ClassA object from ClassB Just use the below code

ClassA objA=MySingleton.getClassAInstance();

Insted of 

 ClassA objA=new ClassA();



package com.awf.org;

public class MySingleton
{
    private volatile static MySingleton instance;
    private volatile static ClassA classAinstance;
  
    private MySingleton()
    {
        // Suppressing creating a new instances
    }
   
     public static MySingleton getInstance()
    {
        if (instance == null) {
            synchronized (MySingleton.class) {
                if (instance == null) {
                    instance = new MySingleton();
                }
            }
        }
        return instance;
    }
   
   
   
public static ClassA getClassAInstance()
    {
      
  if (classAinstance == null) {
            synchronized (ClassA.class) {
                if (classAinstance == null) {
                     classAinstance = new ClassA();
                }
            }
        }
        return classAinstance;

    }

 
}



File 1: ClassA.java
 

package com.awf.org;

public class ClassA{
public void displayMsg(){


System.out.println("Class A method is called");
 

}
}


File 2: ClassB.java

package com.awf.org;

public class ClassB{
public static void main(String args[]){


ClassA objA=
MySingleton.getClassAInstance();
objA.displayMsg();
 

}
}

File 3 :ClassC.java
package com.awf.org;

public class ClassC{


public static void main(String args[]){


ClassA objA=MySingleton.getClassAInstance();
objA.displayMsg();
 

}
}


Output :
If you ClassB  or ClassC you will get the below output

Class A method is called

Note : Without Singleton 2 Objects created for ClassA but now single object is created for ClassA and Usedby ClassB and ClassC

============================================================

Second Way : 

 Make ClassA as Singleton Object .
If you to get ClassA object from ClassB Just use the below code

ClassA objA=ClassA.getClassAInstance();

Insted of 

 ClassA objA=new ClassA();


 File 1: ClassA.java
package com.awf.org;

public class
ClassA
{
   private volatile static ClassA classAinstance;
  
    private
ClassA()
    {
        // Suppressing creating a new instances
    }
   
       
   
public static ClassA getClassAInstance()
    {
      
  if (classAinstance == null) {
            synchronized (ClassA.class) {
                if (classAinstance == null) {
                     classAinstance = new ClassA();
                }
            }
        }
        return classAinstance;

    }

 
public void displayMsg(){

  System.out.println("Class A method is called");
 

}

}




 

File 2: ClassB.java

package com.awf.org;

public class ClassB{
public static void main(String args[]){


ClassA objA=
ClassA.getClassAInstance();
objA.displayMsg();
 

}
}

File 3 :ClassC.java
package com.awf.org;

public class ClassC{


public static void main(String args[]){


ClassA objA=ClassA.getClassAInstance();
objA.displayMsg();
 

}
}


Output :
If you ClassB  or ClassC you will get the below output

Class A method is called

Note : Without Singleton 2 Objects created for ClassA but now single object is created for ClassA and Usedby ClassB and ClassC



Regards,
R Tamilanban M.E(CSE)
AWF Community

 

No comments:

Post a Comment