banner
Jun 15, 2023
114 Views

Abstract Factory

Written by
banner

Abstract Factory provide an interface for creating families of related or dependent objects without specifying their concrete classes

Abstract Factory là một mẫu thiết kế tạo đối tượng (creational design pattern) cho phép bạn tạo ra các tập hợp gần gũi các đối tượng liên quan mà không cần chỉ định các lớp cụ thể của chúng.

Ví dụ công ty bạn là 1 công ty làm game mobile. Bạn muốn chỉ định thiết bị sửa dụng cho các bạn dev mobile là iPhone + macbook, còn mấy ông code backend thì dùng Samsung + Thinkpad.

from abc import ABC, abstractmethod

# Abstract Products
class Laptop(ABC):
    @abstractmethod
    def operation(self):
        pass

class Smartphone(ABC):
    @abstractmethod
    def operation(self):
        pass

# Concrete Laptop
class LaptopMacbook(Laptop):
    def operation(self):
        return "Macbook operation"

class LaptopThinkpad(Laptop):
    def operation(self):
        return "Laptop Thinkpad operation"

# Concrete Smartphone
class SmartphoneSamsung(Smartphone):
    def operation(self):
        return "Smartphone Samsung operation"

class SmartphoneApple(Smartphone):
    def operation(self):
        return "Smartphone Apple operation"

# Abstract Factory
class AbstractFactory(ABC):
    @abstractmethod
    def create_laptop(self):
        pass

    @abstractmethod
    def create_smartphone(self):
        pass

# Concrete Factories
class BackendDeveloper(AbstractFactory):
    def create_laptop(self):
        return LaptopThinkpad()

    def create_smartphone(self):
        return SmartphoneSamsung()

class iOSDeveloper(AbstractFactory):
    def create_laptop(self):
        return LaptopMacbook()

    def create_smartphone(self):
        return SmartphoneApple()

# Usage
if __name__ == "__main__":
    backend_dev = BackendDeveloper()
    laptop_for_be = backend_dev.create_laptop()
    smartphone_for_be = backend_dev.create_smartphone()

    print(laptop_for_be.operation())  # Output: Laptop Thinkpad operation
    print(smartphone_for_be.operation())  # Output: Smartphone Samsung operation

    mobile_dev = iOSDeveloper()
    laptop_mobile_dev = factory2.create_laptop()
    phone_mobile_dev = factory2.create_smartphone()

    print(laptop_mobile_dev.operation())  # Output: Macbook operation
    print(phone_mobile_dev.operation())  # Output: Smartphone Apple operation
Article Categories:
dev
banner

Leave a Reply

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