模式 / 创建型模式
image

from abc import ABCabstractmethod

# --- interfaces ---
class IFactory(ABC):
    @abstractmethod
    def create_a(self) -> "ProductA": ...
    @abstractmethod
    def create_b(self) -> "ProductB": ...

class ProductA(ABC):
    @abstractmethod
    def test_a(self) -> None: ...

class ProductB(ABC):
    @abstractmethod
    def test_b(self) -> None: ...

# --- family 1 ---
class ProductA1(ProductA):
    def test_a(self): print("test A1")

class ProductB1(ProductB):
    def test_b(self): print("test B1")

class Factory1(IFactory):
    def create_a(self): return ProductA1()
    def create_b(self): return ProductB1()

# --- family 2 ---
class ProductA2(ProductA):
    def test_a(self): print("test A2")

class ProductB2(ProductB):
    def test_b(self): print("test B2")

class Factory2(IFactory):
    def create_a(self): return ProductA2()
    def create_b(self): return ProductB2()

# --- client ---
def check_factory(factory: IFactory) -> None:
    factory.create_a().test_a()
    factory.create_b().test_b()

check_factory(Factory1())  # test A1 / test B1
check_factory(Factory2())  # test A2 / test B2