Factory Design Pattern

Factory pattern comes under the creational pattern and it is one of the most commonly used patterns in Java to create an object.

Factory Pattern exposes a common interface which is used to create an object, while hiding the creation logic from the client.


Example Implementation

The figure below shows an implementation of factory pattern.

Factory Design Pattern

We take a simple example of a Burger ordering system. To make it simple, we consider that each of the custom either chooses Veg or Chicken burger in his order.

We have an interface called ‘Burger’, and two concrete classes ‘VegBurger’ and ‘ChickenBurger’ which implement the ‘Burger’ interface. As per the factory pattern the creation logic should be hidden, hence we have the ‘BurgerFactory’ which creates the ‘VegBurger’ or ‘ChickenBurger’ and serves to the client who needs it.

The code of the above implementation is shown below:

Burger.java

public interface Burger {
    public int getPrice();
}

VegBurger.java

public class VegBurger implements Burger{
	
    private final int price = 20;

    public int getPrice() {
	return price;
    }
}

ChickenBurger.java

public class ChickenBurger implements Burger{

    private final int price = 30;
	
    public int getPrice() {
	return price;
    }
}

BurgerFactory.java

public class BurgerFactory {
	
    public static int getBurgerPrice(String burgerType){
	if(burgerType.equals("VEG")){
    	    Burger burger = new VegBurger();
	    return burger.getPrice();
	}
	else if(burgerType.equals("CHICKEN")){
	    Burger burger = new ChickenBurger();
	    return burger.getPrice();
	}
	return 0;
    }
}

BurgerOrder.java

public class BurgerOrder {
	
    public int orderNum;
	
    private String burgerType;
	
    private int quantity;
	
    public BurgerOrder(int orderNum, String type, int quantity){
	this.orderNum = orderNum;
	this.burgerType = type;
	this.quantity = quantity;
    }
	
    public int calculateOrderBill(){
	return BurgerFactory.getBurgerPrice(burgerType) * quantity;
    }
	
    public static void main(String[] args) {
		
	BurgerOrder order = new BurgerOrder(1123,"VEG", 5);
	BurgerOrder order1 = new BurgerOrder(1124, "CHICKEN", 3);
		
	System.out.println("Bill for Order Number "+order.orderNum+ " is 
            "+order.calculateOrderBill());
	System.out.println("Bill for Order Number "+order1.orderNum+ " is 
            "+order1.calculateOrderBill());
    }
}