Java Factory Pattern

  • + 0 comments

    import java.util.Scanner;

    interface Food { public String getType(); }

    class Pizza implements Food { public String getType() { return "Someone ordered a Fast Food!"; } }

    class Cake implements Food { public String getType() { return "Someone ordered a Dessert!"; } }

    class FoodFactory { public Food getFood(String order) { if (order.equalsIgnoreCase("pizza")) { return new Pizza(); } else { return new Cake(); } } }

    public class Solution { public static void main(String args[]) { Scanner sc = new Scanner(System.in); // Read user input String order = sc.nextLine();

        FoodFactory foodFactory = new FoodFactory();
        Food food = foodFactory.getFood(order);
    
        System.out.println("The factory returned class " + food.getClass().getSimpleName());
        System.out.println(food.getType());
    
        sc.close();
    }
    

    }