How to create Factory Design Pattern in Java

 

Already we have seen Fully Singleton Design Pattern in our earlier tutorial, now we will see about Factory Design Pattern. 

Factory design pattern is one is the most important and widely used pattern every where in Java. The factory method pattern defines an interface for creating an object, but let sub-classes decide which class to instantiate based on the user requirement. JDK and most of all frameworks like Spring, Struts etc uses factory design pattern internally. Also factory design pattern can be classified into various types like Static Factory, Service Locator Factory and Abstract Factory. 

Lets see one simple example as getting various Computer instances based on the used requirement. As we already explained above we need to have a interface for creating and Object but sub-classes will decide which class need to be instantiated  As same way we are going to have interface called "Computer" and sub-classes like "Desktop", "WorkStation", "Server", "Laptop" and "SuperComputer" will implement "Computer" interface and will their own method definitions. 



public interface Computer {
 public String myComputerType();
}


public class Desktop implements Computer {
 public String myComputerType() {
  return "You have requested for Desktop";
 }
}


public class WorkStation implements Computer {
 public String myComputerType() {
  return "You have requested for WorkStation";
 }
}


public class Server implements Computer {
 public String myComputerType() {
  return "You have requested for Server";
 }
}


public class Laptop implements Computer {
 public String myComputerType() {
  return "You have requested for Laptop";
 }
}


public class SuperComputer implements Computer {
 public String myComputerType() {
  return "You have requested for SuperComputer";
 }
}



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

  // Based on user requirement we will get the Object
  
  Computer obj = FactoryPattern.getComputerType("desktop");
  if(obj != null) 
   System.out.println(obj.myComputerType());
  
  obj = FactoryPattern.getComputerType("laptop");
  if(obj != null) 
   System.out.println(obj.myComputerType());
  
  obj = FactoryPattern.getComputerType("server");
  if(obj != null) 
   System.out.println(obj.myComputerType());
 }
 
 public static Computer getComputerType(String val){
  if(val.equalsIgnoreCase("desktop")) return new PC();
  else if(val.equalsIgnoreCase("workstation")) return new WorkStation();
  else if(val.equalsIgnoreCase("server")) return new Server();
  else if(val.equalsIgnoreCase("laptop")) return new Laptop();
  else if(val.equalsIgnoreCase("super")) return new SuperComputer();
  return null;
 }
}



OUTPUT:


You have requested for Desktop
You have requested for Laptop
You have requested for Server









No comments:
Write comments