Wednesday, June 29, 2016

Factory Design pattern

This is another most important design pattern and this is the foundation of Spring, Struts and most of frameworks. Specially this is mostly used in JDK also.

The main advantage of using this method is to hide implementation details from the user. Actually this design pattern is developed using Encapsulation concept. It decouples calling from target class.  Look at the following class diagram and example to understand about Factory design pattern.


Look at this example with above diagram.

Animal.java interface

package com.app.designs.factory;

public interface Animal {
    public void eat();
}



Cat.java class

package com.app.designs.factory;

public class Cat implements Animal {

   @Override
   public void eat() {
       System.out.println("Cat eating"); 
   }
}



Dog.java class

package com.app.designs.factory;

public class Dog implements Animal {

   @Override
   public void eat() {
       System.out.println("Dog eating");
   }
}



AnimalFactory.java class

package com.app.designs.factory;

public class AnimalFactory {

   public Animal buildAnimal(String animalType){
  
      if(animalType==null){
          return null;
      }
      if("dog".equalsIgnoreCase(animalType)){
          return new Dog();
      }
      if("cat".equalsIgnoreCase(animalType)){
          return new Cat();
      }
      return null;
   }
}



Application.java class

package com.app.designs.factory;

public class Application {

   public static void main(String[] args) {
      String animalType = "cat";
  
      AnimalFactory factory = new AnimalFactory();
      Animal animal = factory.buildAnimal(animalType);
      animal.eat();
   }
}




In this example I want to create a cat instance. Then you will be able to see it creates a new Cat object. If you want a Dog object, you need to set animalType to dog. Then it will create a new Dog object. According to the user requirement, system will produce the requested abject. 

This is the core concept behind Spring and Struts frameworks. You may know that there is a concept behind Spring framework called "Dependency Injection". To make it loosely coupled, it uses this factory design pattern inside the framework.


Advantages of Factory design pattern

  • Make code loosely coupled 
  • Hide implementation details from outside

Disadvantages of Factory design pattern

  • It looks your code is more abstract
  • Code becomes complex