Singleton Design Pattern in java

Problem:

  • Instead of creating multiple objects of same class having same data and wasting memory, degrading performance it is recommended to create only one object and use it multiple times.

Solution:

  •  Use Singleton Java Class.
  • Java class that allows us to create one object per JVM is is called as singleton java class.
  • The logger class of  Log 4J API is given as singleton java class.

Rules:

  • It must have only private constructors.
  • It must have private static reference variable of same class.
  • It must have public static factory method having the logic of singleton.
  • Static method should create and return only one object.
  • All these rules close all the doors of creating objects for java class and opens only one door to create object.
  • factory method where singleton logic is placed
  • The method of a class capable of creating and returning same class or other class object is known as factory method.

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.  
  22. return object;
  23.  
  24. }
  25.  
  26. }
     

  1. package instanceofjava;
  2.  
  3. public class SingletonObjectDemo {

  4. public static void main(String args[]) {
  5.  
  6.      SingletonClass s1= SingletonClass .getInstance();
  7.      SingletonClass s2= SingletonClass .getInstance();
  8.      System.out.println(s1.hashCode());
  9.      System.out.println(s2.hashCode());
  10.  
  11. }
  12. }

Output:

  1. getInstance(): First time getInstance was called and object created !
  2. Singleton(): Private constructor invoked
  3. 655022016
  4. 655022016


Make the Factory method Synchronized to prevent from Thread Problems:


  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static synchronized  SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.   
  22. return object;
  23.  
  24. }
  25.  
  26. }

Override the clone method to prevent cloning:

 

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object;
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static synchronized  SingletonClass getInstance()
  12. {
  13.  
  14. if (object == null)
  15. {
  16.  
  17. System.out.println("getInstance(): First time getInstance was called and object created !");
  18. object = new SingletonClass ();
  19.  
  20.  }
  21.  else 
  22. return object;
  23.  
  24.  
  25. public Object clone() throws CloneNotSupportedException {
  26.  
  27. throw new CloneNotSupportedException();
  28.  
  29. }
  30.  
  31. }

Eager Initialization:

  • In eager initialization object of the class will be created when class loading itself its easy way to create singleton but its having one disadvantage that even though nobody needs it still it creates object.

  1. package com.instanceofjava;
  2.  
  3. public class SingletonClass {

  4. private static SingletonClass object= new SingletonClass ();
  5.  
  6. private SingletonClass ()
  7. {
  8.         System.out.println("Singleton(): Private constructor invoked");
  9. }
  10.  
  11. public static SingletonClass getInstance()
  12. {
  13.  
  14. return object;
  15.  
  16. }
  17.  
  18. }
     


Lazy Initialization:

  • When ever client needs object it will check for whether object is created or not if not it will create otherwise it will return created object
  • First basic example shows lazy initialization.


Static Block Initialization:

  • This is similar to eager initialization except that in this we create object in static block and we can place exception logic.

  1. package com.instanceofjava;
  2.  
  3. public class StaticBlockSingleton {
  4.  
  5. private static StaticBlockSingleton object;
  6.  
  7. private StaticBlockSingleton(){}
  8.  
  9.     //static block initialization for exception handling
  10. static{
  11.  
  12.  try{
  13.  
  14.             object = new StaticBlockSingleton();
  15.  
  16.         }catch(Exception e){
  17.  
  18.             throw new RuntimeException("Exception occured in creating singleton object");
  19. }
  20. }
  21.  
  22. public static StaticBlockSingleton getInstance(){
  23.         return object;
  24. }
  25.  
  26. }


Factory Method Pattern


Factory Method Pattern:

  • Problem: Using new keyword we can not create object with flexibility and by applying restrictions.
  • Solution: Use Factory pattern (or) Factory method.
  • By defining a abstract class or an interface but let the subclass  decide which class object to instantiate.
  • A method of a class capable of constructing and returning its own class object or other class object is called "factory method".
  • There are two types of factory methods.
  1. Static factory method.
  2. Instance factory method.

 1.Static Factory method:

  • A static method defined to construct and return object of same class or different is known as static factory method.
  • Some of the pre defined static factory methods are as follows.
  1. Thread th= Thread.currentThread();
  2. Class c=Class.forName();
  3. Runtime rt=Runtime.getRuntime();
  4. Calendar c=Calendar.getInstance();

2.Instance Factory method:

  • A non static method defined to construct and return object of same class or different is known as instance factory method.
  • Some of the pre defined instance factory methods are as follows.
  1.  String s= new String("instance of");
     String s1=s.concat("java");
  2. StringBuffer sb=new StringBuffer("instance of");
    sb=sb.subString(0,2);
  3. Date d= new Date();
    String s=d.toString();
Program on Factory method / Factory Design pattern:

Step 1: create an interface:

  1. package com.instanceofjavaforus;
  2.  
  3. public interface Vehicle {
  4.  
  5.  public void engine();
  6.  
  7. }
     

 Step 2: create a Two Wheeler class which implements vehicle interface:

  1. package com.instanceofjavaforus;
  2.  public class TwoWheeler implements Vehicle {
  3.  
  4.    @Override
  5.     public void engine() {
  6.         System.out.println("Two Wheeler");
  7.     }
  8.  
  9. }

Step 3:: create a Four Wheeler class which implements vehicle interface:

  1. package com.instanceofjavaforus;
  2.  public class FourWheeler implements Vehicle {
  3.  
  4.    @Override
  5.     public void engine() {
  6.         System.out.println("FourWheeler");
  7.     }
  8.  
  9. }

Step 4: create a SixWheeler class which implements vehicle interface:

  1. package com.instanceofjavaforus;
  2.  public class SixWheeler implements Vehicle {
  3.  
  4.    @Override
  5.     public void engine() {
  6.         System.out.println("SixWheeler");
  7.     }
  8.  
  9. }

Step 5: create a TestEngine class which is having factory method:

  1. package com.instanceofjavaforus;
  2.  public class TestEngine {
  3.  public Vehicle getVehicle(String venname){
  4.      if(venname==null){
  5.             return null;
  6.        }else if(venname.equalsIgnoreCase("TwoWheeler")){
  7.             return new TwoWheeler();
  8.         }else if(venname.equalsIgnoreCase("FourWheeler")){
  9.             return new FourWheeler();
  10.         }else if(venname.equalsIgnoreCase("SixWheeler")){
  11.             return new SixWheeler();
  12.         }
  13.     
  14.         return null;
  15.     }
  16. }

Step 6: create a FactoryDemo class:

  1. package com.instanceofjavaforus;
  2.  public class FactoryDemo {
  3.   public static void main(String args[]){
  4.  
  5.      TestEngine te= new TestEngine();
  6.  
  7.         Vehicle vehcle1=te.getVehicle("TwoWheeler");
  8.        vehcle1.engine();
  9.  
  10.         Vehicle vehcle2=te.getVehicle("FourWheeler");
  11.         vehcle2.engine();
  12.  
  13.         Vehicle vehcle3=te.getVehicle("SixWheeler");
  14.          vehcle3.engine();
  15.  }
  16. }

  1. OutPut:
  2. TwoWheeler
  3. FourWheeler
  4. SixWheeler

Design patterns in java


Design patterns:

  • Pattern means set of guide lines.
  • Design patterns are solutions to commonly reoccurring problems in software development.
  • Design patterns are well proven solutions to common software problems.
  • Design patterns are best practices to use software technologies effectively in application development.  
  • Design patterns used in analysis and requirement  phase of  SDLC.
  • Design patterns can be implemented by using programming language.

Advantages:

  • Reusable.
  • These are already defined solutions to common re occurring problems so it reduces time.
  • They are already defined so Easy to understand and debug.

Categorization:

  • These are categorized into two parts.
  1. Java SE Design patterns.
  2. Java EE Design patterns.

Java SE Design patterns: 

  •  In Java SE there are mainly three types.

1.Creational Design patterns:

  1. Factory Pattern
  2. Abstract Factory Pattern
  3. Singleton Pattern
  4. Prototype Pattern
  5. Builder Pattern.

2.Structural Design patterns:

  1. Adapter Pattern
  2. Bridge Pattern
  3. Composite Pattern
  4. Decorator Pattern
  5. Facade Pattern
  6. Flyweight Pattern
  7. Proxy Pattern

3.Behavioral Design patterns:

  1. Chain Of Responsibility Pattern
  2. Command Pattern
  3. Interpreter Pattern
  4. Iterator Pattern
  5. Mediator Pattern
  6. Memento Pattern
  7. Observer Pattern
  8. State Pattern
  9. Strategy Pattern
  10. Template Pattern
  11. Visitor Pattern
Read More:
Factory pattern


Select Menu