Skip to content

Factory Design Pattern

Devrath edited this page Dec 2, 2023 · 1 revision

industries-banner

Gangs of Four(GOF) - Definition

This design pattern takes the responsibility of instantiating the object from the existing class to the factory class.

General reference scenario

  • Assume that there is a factory 🏭 that prepares the coffee for the customer.
  • Assume the coffee factory can prepare hundreds of types of coffee.
  • Customer has the option to select the coffee type from the menu and provide the input to the coffee factory
  • The customer does not know how the coffee gets created because it's a complex process.
  • All the customer does is input to the factory, Hey I need this coffee and the coffee factory decides which mechanism can be used to prepare the coffee based on the input the customer is provided and returns that specific type of coffee.
  • Now the customer can enjoy the delirious coffee once the coffee gets delivered to the customer.

Programming example

Coffee.java

public interface Coffee {
    String name();
    Boolean isHot();
}

CoffeeAmericano.java

public class CoffeeAmericano implements Coffee {
    @Override
    public String name() { return "CoffeeAmericano";}
    @Override
    public Boolean isHot() { return false; }
}

CoffeeLatte.java

public class CoffeeLatte implements Coffee {
    @Override
    public String name() { return "CoffeeLatte"; }
    @Override
    public Boolean isHot() { return true; }
}

CoffeeType.java

public enum CoffeeType {
    COFFEE_LATTE, COFFEE_AMERICANO
}

CoffeeFactory.java

public class CoffeeFactory {

    CoffeeType coffeeType;

    CoffeeFactory(CoffeeType coffeeType) {
        this.coffeeType = coffeeType;
    }

    public Coffee getCoffee(){
        if(coffeeType==CoffeeType.COFFEE_LATTE){
            return new CoffeeLatte();
        }else if(coffeeType==CoffeeType.COFFEE_AMERICANO) {
            return new CoffeeAmericano();
        }else{
            throw new IllegalArgumentException();
        }
    }
}

Main.java

public class Main {
    public static void main(String[] args) {
        // Creating the factory instance: -> Observe We just pass Type
        CoffeeFactory factory = new CoffeeFactory(CoffeeType.COFFEE_AMERICANO);
        // We create the coffee from factory object
        Coffee coffee = factory.getCoffee();
        // Now we can access the implementations of factory
        System.out.println("CoffeeName:-> "+coffee.name());
        System.out.println("CoffeeStatusIsItHot:-> "+coffee.isHot());
    }
}

Output

CoffeeName:-> CoffeeAmericano
CoffeeStatusIsItHot:-> false

Programming example observation

  • It helps in keeping all the creation of objects in place
  • If a lot of object types are involved, the factory class itself might become bloated and hard to test since one class itself is responsible for all the creation parts.