This content originally appeared on DEV Community and was authored by Prashant Mishra
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();
}
}
This content originally appeared on DEV Community and was authored by Prashant Mishra
Prashant Mishra | Sciencx (2024-08-26T15:53:47+00:00) Factory method. Retrieved from https://www.scien.cx/2024/08/26/factory-method-2/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.