Factory method
Prashant Mishra
Posted on August 26, 2024
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:
public interface Burger {
public void getBurger();
}
public class CheeseBurger implements Burger {
@Override
public void getBurger() {
System.out.println("Cheeseburger for you !");
}
}
public class DeluxBurger implements Burger{
@Override
public void getBurger(){
System.out.println("DeluxBurger for you!");
}
}
public class VeganBurger implements Burger{
@Override
public void getBurger() {
System.out.println("VeganBurger for you!");
}
}
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;
}
}
}
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();
}
}
Posted on August 26, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.