What is Factory Design Pattern?

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.

Table of Contents

Real Life Examples of Factory Design Pattern

Example 1:

Factory Design Pattern Real-time ExampleLet’s suppose, I am a customer of the shop, where I arrive to buy soap. I ask the shopkeeper for either a Hamam soap, a Rexona soap or a Lux soap. The shopkeeper analyses my request and based on my request; he decides which soap needs to be returned. Here the shopkeeper is acting like a Factory.

Example 2:

Factory Design Pattern OS ExampleLet’s suppose, I am a phone manufacturer, and I am looking for Operating Systems (OS) for various phones, but I don’t have any knowledge about a suitable OS for a particular phone. I will contact an OS factory for that. If I ask for an OS of an iPhone, OS factory would analyze the request and return the iOS, which is the recommended OS for iPhone. If the next time, a phone manufacturer approaches OS factory for an Operating System for a Samsung mobile, the OS factory will know that since the request is for Samsung, the suitable return will be an Android OS. Similarly, if the phone manufacturer asks for an OS for a Nokia phone, the OS factory would return the Windows OS based on the client’s recommendation. Here the phone manufacturer isn’t aware of the creational procedure of the OS because the object creation is hidden from him. It’s the responsibility of the OS factory to provide a suitable OS. Here the OS factory will act as a Factory where the object creation is done using the input like iPhone, Samsung, Nokia. Based on the input the best object will be returned.

Example 3:

software development sample photoIf you are working in a software company, you’d have noticed this kind of a scenario. Let’s suppose; I have two clients, a Bank client and some owner of a small-scale shop. First, the bank client approaches the manager and asks for the best UI developer available for a contract purpose. The manager analyzes the resources that are the UI developers and picks the best option for the client’s objective. Now the small shop owner approaches and requests for a UI developer in a limited amount of money. Here the criterion is UI developer in less money. The manager will analyze the request based on this criterion and picks the suitable option. In this example, the clients don’t have any knowledge about the UI developers. They are requesting the manager for a UI developer suitable for their criteria. The manager here acts as a Factory.

Advantages of Factory Design Pattern

  • The end user needn’t worry about the technical details about object creation.
  • Factory Method Pattern gives full control or access to the sub-classes to choose the type of objects to create.
  • The main moto of Factory Design Pattern is to hide the technical details behind the object type selection and creation for the client code. It promotes the loose-coupling, so the client code interacts only with the interface or abstract methods instead of implemented classes. 

When to use Factory Design Pattern?

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.

UML Diagram of Factory Design Pattern

Factory Design Pattern Java Implementation

Step 1: Create an abstract class "Food" which has two variables called "billPerPerson" and "items"

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;
    }
}

Step 2: Create concrete classes that extend the abstract class "Food"

  • Here “VegFood” and “NonVegFood” are classes having some common fields. That’s the reason why this class is defined as abstract. 
  • Let’s suppose, there is another food called, Italian food having bill per person item then that Italian food extends food class. Hence food class is defined as abstract. So, these two fields are common for both the “Veg” and “NonVeg” classes, that’s why they are defined under food class.
  • Then there’s a constructor. Here we will set the bill per person. For both the “Veg” and “NonVegFood” classes, there will be some rates assigned.
  • For “VegFood”, there will be “Idly”, “Dosa”, “Vada”. For “NonVegFood”, there will be “Biryani” and “Chicken”.
  • Though the data is unique, since the fields are common, these are defined common under food class.
  • Since the “VegFood” extends “Food” class, all the methods and variable would be extended to this “VegFood”. Using that, we will call the Super Class Constructor using “super” keyword. It will set the bill per person for “VegFood” and include “Idly”, “Dosa”, “Vada” under “VegFood”.
  • Same will happen in the case of “NonVegFood”. It extends the “Food” class too. So, all the methods and variable will be extended to “NonVegFood” and using “super” word for Super Class Constructor, we will set the bill person for “NonVegFood”.
  • For “NonVegFood” the rate would be 120, and for “VegFood” the rate would be 100. And then we will add the items, using “Items.add”. 
  • Then comes the Factory Design Class, which can be related to the food server in that restaurant who get the request from the customer regarding Food type.
  • If the customer requests for veg food type, it will return the “VegFood” object by creating it. If the request is otherwise, that is nonveg food type, the food server will return the “NonVegFood” object after creating it.
  • Both the “VegFood” and “NonVegFood” will be extended by the “Food” class, since the Food class is the abstract class for both of them.
  • The first criterion for the Factory Class Method is that it should be static. The reason for its similarity with the utility method. You can call this method without creating the objects. The second criterion is that it should send the input for deciding the type of the object. Here the food type is input based on which the object would be decided later it would be written.
  • If the customer asks for the Italian food, it will return null since the restaurant doesn’t serve Italian food. These are the scenarios of the Factory Class Method. 
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");
    }
}

Step 3: Create a FoodServer which is a Factory class to create an object for concrete based on the information

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;
        }
    }
}

Step 4: Main class "Customer" to get the required Food based on the food type

  • In the main class, there are two customers. “Customer1” and “Customer2”. “Customer1” is asking the food server for “VegFood” details. The input here is the food type, veg. “Veg.=Veg”. It will return the “VegFood” object. “Customer2” is asking the food server for “NonVegFood” details. The input here is the food type, nonveg. “NonVeg. = NonVeg”. It will return the “NonVegFood” object.
  • If there is a third customer and it asks for Italian Food. It will return the null object.
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());
    }
}