banner
Jun 20, 2023
111 Views

Factory Method pattern

Written by
banner

The factory method pattern is a creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created.

Factory Method là một mẫu thiết kế (design pattern) trong lập trình, được sử dụng để tạo ra các đối tượng mà không cần chỉ định rõ lớp cụ thể của đối tượng đó. Factory Method cho phép chúng ta chọn loại đối tượng cần tạo dựa trên một điều kiện hoặc thông số, giúp tăng tính linh hoạt và mở rộng của mã.

Ví dụ: Bạn có 1 app tự động gợi ý món ăn cho người dùng tùy khung giờ. Lúc này bạn có thể tạo ra các class Breakfast, Lunch, Dinner riêng nhưng nếu có thêm các bữa khác trong ngày (ví dụ ở Anh có bữa trà chiều chẳng hạn) thì bạn lại phải lật đật đi sửa trong client code.

Thay vì như thế bạn có thể dùng Factory Method để tạo ra các bữa ăn tùy thuộc vào giờ giấc trong ngày. Nếu sau này thêm loại bữa ăn nào thì chỉ cần client code truyền đúng giờ sẽ có được bữa ăn như ý.

from abc import ABC, abstractmethod
class Eat:
    def foods(self):
        pass

class Breakfast(Eat):
    def foods(self):
        return "Hard boiled eggs !"

class Lunch(Eat):
    def foods(self):
        return "Hamburger !"

class Dinner(Eat):
    def foods(self):
        return "Steak !"

# Dùng factory để tạo class dựa trên điều kiện
class MealFactory:
    @staticmethod
    def choose_meals(hour):
        if hour< 10:
            return Breakfast()
        elif hour < 16:
            return Lunch()
        elif hour < 23:
            return Dinner()
        else:
            raise ValueError("Invalid hour.")

# Sử dụng Factory Method - client code
food_factory = MealFactory()
having_breakfast = food_factory.choose_meals(5)
having_dinner = food_factory.choose_meals(20)

print(having_breakfast.foods())  # Output: "Hard boiled eggs !"
print(having_dinner.foods())    # Output: "Steak !"
Article Categories:
dev
banner

Leave a Reply

Your email address will not be published. Required fields are marked *