Factory Design Pattern falls under the category of Creational Design Pattern. Since the primary motive of the Creational Design Pattern is to create and initialize the objects. The same objective is passed onto the Factory Design Pattern. So, we can define the Factory Design Pattern as the creation of the objects without the exposition of the creational logic to its client.
The factory design pattern is used when we have a superclass with multiple sub-classes and based on the input; we need to return one of the sub-class.
Example: If a Restaurant serves Veg food, Non-Veg food, and Italian food.
Treat VegFood, NonVegFood, and ItalianFood as three classes whose superclass is Food.
If a customer asks “Veg” then Factory method would return the “VegFood” class.
public abstract class Food { protected double billPerPerson; protected Set items; public Food(double billPerPerson) { this.billPerPerson=billPerPerson; this.items=new HashSet<>(); } public double getBill() { return billPerPerson; } public Set getItems() { return items; } }
public class VegFood extends Food { public VegFood() { super(100); items.add("Idly"); items.add("Dosa"); items.add("Vada"); } }
public class NonVegFood extends Food { public NonVegFood() { super(120); items.add("Biriyani"); items.add("Chicken 65"); } }
public class FoodServer { public static Food getFood(String foodType) { if (foodType.equals("veg")) { return new VegFood(); } else if (foodType.equals("non veg")) { return new NonVegFood(); } else { System.out.println("We are not serving " + foodType); return null; } } }
public class Customer { public static void main(String[] args) { Food customer1Food = FoodServer.getFood("veg"); System.out.println("Customer1"); System.out.println("Items: "+customer1Food.getItems().toString()); System.out.println("Bill: "+customer1Food.getBill()); Food customer2Food = FoodServer.getFood("non veg"); System.out.println("Customer1"); System.out.println("Items: "+customer2Food.getItems().toString()); System.out.println("Bill: "+customer2Food.getBill()); } }