DEV Community

Prashant Mishra
Prashant Mishra

Posted on • Edited on

Factory method

It is part of Creational design pattern, gives you the concrete objects without you having to worry about how it is doing it.
For example, there is a factory called BurgerFactory, that can give you Burger of different types like CheeseBurger, DeluxBurger, and VeganBurger.
You just have to specify the kind of Burger you want and it gives you the that Burger ( You don't know/care how it is created )

Use Case: Use the Factory Method when you have a single family(Burger) of related products(CheeseBurger,DeluxBurger, VeganBurger) and want to delegate the creation of those products to subclasses. It's particularly useful when you want to manage the creation of objects that are part of a single hierarchy

Structure:
Product: Defines the interface for objects the factory method creates.
ConcreteProduct: Implements the Product interface.
Creator: Declares the factory method, which returns an object of type Product.

Let us understand Factory Method with the same example:

Image description

public interface Burger {
    public void getBurger();
}
Enter fullscreen mode Exit fullscreen mode
public class CheeseBurger implements Burger {

    @Override
    public void getBurger() {
        System.out.println("Cheeseburger for you !");
    }

}

Enter fullscreen mode Exit fullscreen mode

public class DeluxBurger  implements Burger{
    @Override
    public void getBurger(){
        System.out.println("DeluxBurger for you!");
    }
}
Enter fullscreen mode Exit fullscreen mode

public class VeganBurger implements Burger{

    @Override
    public void getBurger() {
        System.out.println("VeganBurger for you!");
    }

}

Enter fullscreen mode Exit fullscreen mode

public class BurgerFactory {
    public Burger getBurgerForCustomer(String burgerType){
        switch (burgerType) {
            case "cheese": return  new CheeseBurger();
            case "delux": return new DeluxBurger();
            case "vegan": return new VeganBurger();
            default: return null;

        }
    }
}
Enter fullscreen mode Exit fullscreen mode
public class BurgerJointMain {
    public static void main(String args[]){
        BurgerFactory factory = new BurgerFactory();
        Burger burger = factory.getBurgerForCustomer("cheese");// use can ask for "vegan" or "delux" burger as well
        burger.getBurger();

    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)