1ae1de6d0d2a87e6834da409bfd891b2 Factory Method

Factory Method

 


What is the Factory Method?

The Factory Method is a design pattern used in object-oriented programming (OOP) to create objects without specifying their exact class. Instead of directly using a new keyword to instantiate an object, a factory method delegates the object creation to a subclass or a separate factory class.

It is part of the Creational Design Patterns in the Gang of Four (GoF) design patterns and promotes loose coupling and scalability in software development.


Key Features of Factory Method:

Encapsulates object creation logic
Supports flexibility & maintainability
Reduces dependency on concrete classes
Follows Open-Closed Principle (OCP)


Here is a Factory Method implementation in Python for a restaurant order system where users can order Burger, Pizza, or Cold Drinks.


Python Code for Restaurant Ordering System (Factory Method)


from abc import ABC, abstractmethod # Step 1: Define an abstract base class (Interface) class FoodItem(ABC): @abstractmethod def prepare(self): pass # Step 2: Implement Concrete Classes class Burger(FoodItem): def prepare(self): return "Preparing a delicious Burger 🍔" class Pizza(FoodItem): def prepare(self): return "Baking a cheesy Pizza 🍕" class ColdDrink(FoodItem): def prepare(self): return "Serving a refreshing Cold Drink 🥤" # Step 3: Implement Factory Method class FoodFactory: @staticmethod def get_food(order_type): if order_type.lower() == "burger": return Burger() elif order_type.lower() == "pizza": return Pizza() elif order_type.lower() == "cold drink": return ColdDrink() else: return None # Step 4: Take User Input and Use Factory Method print("Welcome to the Restaurant! 🍽️") print("Menu: Burger, Pizza, Cold Drink") order = input("What would you like to order? ").strip() food = FoodFactory.get_food(order) if food: print(food.prepare()) # Output: Message based on order else: print("Sorry, we don't serve that item. Please choose from the menu.")

How This Works:

  1. Defines an abstract class FoodItem (interface) with a prepare() method.
  2. Implements concrete classes (Burger, Pizza, ColdDrink), each defining its own prepare() method.
  3. Creates a FoodFactory class with a get_food() method that returns the appropriate object.
  4. User inputs their order, and the factory returns the correct food item.

Example Run (User Interaction)


Welcome to the Restaurant! 🍽️ Menu: Burger, Pizza, Cold Drink What would you like to order? pizza Baking a cheesy Pizza 🍕

Java Version of the Same Factory Method Pattern


import java.util.Scanner; // Step 1: Define an Interface interface FoodItem { void prepare(); } // Step 2: Implement Concrete Classes class Burger implements FoodItem { public void prepare() { System.out.println("Preparing a delicious Burger 🍔"); } } class Pizza implements FoodItem { public void prepare() { System.out.println("Baking a cheesy Pizza 🍕"); } } class ColdDrink implements FoodItem { public void prepare() { System.out.println("Serving a refreshing Cold Drink 🥤"); } } // Step 3: Implement Factory Method class FoodFactory { public static FoodItem getFood(String orderType) { if (orderType.equalsIgnoreCase("burger")) { return new Burger(); } else if (orderType.equalsIgnoreCase("pizza")) { return new Pizza(); } else if (orderType.equalsIgnoreCase("cold drink")) { return new ColdDrink(); } return null; } } // Step 4: Take User Input and Use Factory Method public class RestaurantOrder { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Welcome to the Restaurant! 🍽️"); System.out.println("Menu: Burger, Pizza, Cold Drink"); System.out.print("What would you like to order? "); String order = scanner.nextLine().trim(); FoodItem food = FoodFactory.getFood(order); if (food != null) { food.prepare(); } else { System.out.println("Sorry, we don't serve that item. Please choose from the menu."); } scanner.close(); } }

Advantages of Using Factory Method in Restaurant Ordering

Encapsulation: Order processing is separate from object creation.
Scalability: Easy to add new food items like Pasta, Salad, etc. without changing existing code.
Flexibility: User can order different items dynamically.



practice:Restaurant Order Management Using Factory Pattern,

 Imagine you are building a system for a restaurant that serves different types of meals. The restaurant menu includes: •VegMeal •NonVegMeal •Drink 

The task is to implement a system that uses the Factory Pattern to create instances of different menu items (VegMeal, NonVegMeal, Drink). The system should allow the user to request a specific item from the menu, and the factory will handle the creation of that item


Steps to Implement:

  1. Create an abstract base class MenuItem – Common interface for all food items.
  2. Implement concrete classes (VegMeal, NonVegMeal, Drink) – Each meal type has its own implementation.
  3. Create a MealFactory class – Generates meal objects based on user input.
  4. Develop a restaurant_order function – Takes user input and uses the factory to create meal objects.

code in python: 

from abc import ABC, abstractmethod # Step 1: Define an Abstract Class for Menu Items class MenuItem(ABC): @abstractmethod def prepare(self): pass # Step 2: Implement Concrete Classes (VegMeal, NonVegMeal, Drink) class VegMeal(MenuItem): def prepare(self): return "Preparing a healthy Veg Meal 🥗" class NonVegMeal(MenuItem): def prepare(self): return "Cooking a delicious Non-Veg Meal 🍗" class Drink(MenuItem): def prepare(self): return "Serving a refreshing Drink 🥤" # Step 3: Implement the Factory Class class MealFactory: @staticmethod def get_meal(meal_type): meal_type = meal_type.lower() if meal_type == "vegmeal": return VegMeal() elif meal_type == "nonvegmeal": return NonVegMeal() elif meal_type == "drink": return Drink() else: return None # Step 4: Function to Take User Input and Use Factory Method def restaurant_order(): print("Welcome to the Restaurant! 🍽️") print("Menu: VegMeal, NonVegMeal, Drink") order = input("What would you like to order? ").strip() meal = MealFactory.get_meal(order) if meal: print(meal.prepare()) # Output based on the order else: print("Sorry, we don't serve that item. Please choose from the menu.") # Step 5: Run the Restaurant Ordering System if __name__ == "__main__": restaurant_order()

How It Works:

  1. Defines an abstract class MenuItem (interface) with a prepare() method.
  2. Implements concrete classes (VegMeal, NonVegMeal, Drink) each with their own prepare() method.
  3. Creates a MealFactory class that provides a static method to return the correct object based on user input.
  4. The restaurant_order() function:
    • Takes user input (e.g., "VegMeal")
    • Calls MealFactory.get_meal(order)
    • Prints the appropriate preparation message

Example Run (User Interaction)


Welcome to the Restaurant! 🍽️ Menu: VegMeal, NonVegMeal, Drink What would you like to order? NonVegMeal Cooking a delicious Non-Veg Meal 🍗


code in java:

import java.util.Scanner; // Step 1: Define an Interface for Menu Items interface MenuItem { void prepare(); } // Step 2: Implement Concrete Classes (VegMeal, NonVegMeal, Drink) class VegMeal implements MenuItem { public void prepare() { System.out.println("Preparing a healthy Veg Meal 🥗"); } } class NonVegMeal implements MenuItem { public void prepare() { System.out.println("Cooking a delicious Non-Veg Meal 🍗"); } } class Drink implements MenuItem { public void prepare() { System.out.println("Serving a refreshing Drink 🥤"); } } // Step 3: Implement the Factory Class class MealFactory { public static MenuItem getMeal(String mealType) { if (mealType.equalsIgnoreCase("VegMeal")) { return new VegMeal(); } else if (mealType.equalsIgnoreCase("NonVegMeal")) { return new NonVegMeal(); } else if (mealType.equalsIgnoreCase("Drink")) { return new Drink(); } return null; } } // Step 4: Use the Factory in a Restaurant Ordering System public class Restaurant { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Welcome to the Restaurant! 🍽️"); System.out.println("Menu: VegMeal, NonVegMeal, Drink"); System.out.print("What would you like to order? "); String order = scanner.nextLine().trim(); MenuItem meal = MealFactory.getMeal(order); if (meal != null) { meal.prepare(); // Output based on the order } else { System.out.println("Sorry, we don't serve that item. Please choose from the menu."); } scanner.close(); } }

How It Works:

  1. MenuItem Interface: Defines a common prepare() method for all meal types.
  2. Concrete Classes (VegMeal, NonVegMeal, Drink): Implement the prepare() method with a unique message.
  3. Factory Class (MealFactory): Uses a static method to return the correct food item based on user input.
  4. Main Class (Restaurant):
    • Takes user input (e.g., "VegMeal")
    • Calls MealFactory.getMeal(order) to get the correct meal object
    • Calls prepare() to print the appropriate message


Post a Comment

0 Comments