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)
How This Works:
- Defines an abstract class
FoodItem
(interface) with aprepare()
method. - Implements concrete classes (
Burger
,Pizza
,ColdDrink
), each defining its ownprepare()
method. - Creates a
FoodFactory
class with aget_food()
method that returns the appropriate object. - User inputs their order, and the factory returns the correct food item.
Example Run (User Interaction)
Java Version of the Same Factory Method Pattern
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:
- Create an abstract base class
MenuItem
– Common interface for all food items. - Implement concrete classes (
VegMeal
,NonVegMeal
,Drink
) – Each meal type has its own implementation. - Create a
MealFactory
class – Generates meal objects based on user input. - 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:
- Defines an abstract class
MenuItem
(interface) with aprepare()
method. - Implements concrete classes (
VegMeal
,NonVegMeal
,Drink
) each with their ownprepare()
method. - Creates a
MealFactory
class that provides a static method to return the correct object based on user input. - The
restaurant_order()
function:- Takes user input (e.g.,
"VegMeal"
) - Calls
MealFactory.get_meal(order)
- Prints the appropriate preparation message
- Takes user input (e.g.,
Example Run (User Interaction)
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:
MenuItem
Interface: Defines a commonprepare()
method for all meal types.- Concrete Classes (
VegMeal
,NonVegMeal
,Drink
): Implement theprepare()
method with a unique message. - Factory Class (
MealFactory
): Uses a static method to return the correct food item based on user input. - 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
0 Comments