Showing posts with label Factory class. Show all posts
Showing posts with label Factory class. Show all posts

Simple Factory Design Pattern class

Lets design simple Factory Design Pattern example with code, like how to design a Factory class and how to get objects from factory. 

Consider the scenario that showroom needs application to access their various Car details through online. Like Car1 runs on Petrol and gives mileage upto 28 KM/L and Car2 runs on Diesel and gives mileage upto 24 KM/L. 
Lets create simple Factory Class to create car objects based on parameter information's.

AANND



public interface Car {
 public String getCallDetails();
}



public class Alto implements Car{

 public String getCallDetails() {
  return "Alto runs on Petrol and gives mileage upto 18 KM/L";
 }
}



public class Swift implements Car{

 public String getCallDetails() {
  return "Swift runs on Diesel and gives mileage upto 24 KM/L";
 }
}



public class CarFactory {

 public static Car getCar(String carName){
  
  Car car = null;
  
  if(carName.equalsIgnoreCase("alto")){
   car = new Alto();
  
  }else if(carName.equalsIgnoreCase("swift")){
   car = new Swift();    
  }
  
  return car;
 }
}



public class ShowRoomApplication {

 public static void main(String[] args) {
  
  Car car1 = CarFactory.getCar("alto");
  String details = car1.getCallDetails();
  System.out.println(details);
  
  Car car2 = CarFactory.getCar("swift");
  details = car2.getCallDetails();
  System.out.println(details);
  
  
 }
}



Output:


Alto runs on Petrol and gives mileage upto 28 KM/L
Swift runs on Diesel and gives mileage upto 24 KM/L