📅  最后修改于: 2023-12-03 15:41:45.188000             🧑  作者: Mango
抽象工厂模式是一种创建型设计模式,旨在通过提供接口创建一系列相关或独立对象,而无需指定它们的具体类。该模式与工厂方法模式相似,但针对多个产品族而非单个产品。
#抽象工厂模式示例代码
from abc import ABC, abstractmethod
class BaseOperation(ABC):
@abstractmethod
def calculate(self, x, y):
pass
class AddOperation(BaseOperation):
def calculate(self, x, y):
return x + y
class SubOperation(BaseOperation):
def calculate(self, x, y):
return x - y
class BaseFactory(ABC):
@abstractmethod
def create_op_one(self):
pass
@abstractmethod
def create_op_two(self):
pass
class AddFactory(BaseFactory):
def create_op_one(self):
return AddOperation()
def create_op_two(self):
return AddOperation()
class SubFactory(BaseFactory):
def create_op_one(self):
return SubOperation()
def create_op_two(self):
return SubOperation()
def client_code(factory: BaseFactory) -> None:
op_one = factory.create_op_one()
op_two = factory.create_op_two()
x = 10
y = 5
print(op_one.calculate(x, y))
print(op_two.calculate(x, y))
add_factory = AddFactory()
sub_factory = SubFactory()
print("Testing add factory:")
client_code(add_factory)
print("\n")
print("Testing sub factory:")
client_code(sub_factory)
代码解释:
BaseOperation
: 定义了抽象产品类AddOperation
和 SubOperation
: 具体产品类,分别实现了 BaseOperation
接口BaseFactory
: 定义了抽象工厂类,其中 create_op_one
和 create_op_two
是工厂方法,用于创建产品实例。AddFactory
和 SubFactory
: 具体工厂类,实现了 BaseFactory
接口,并分别返回了 AddOperation
和 SubOperation
对象。client_code
: 获取工厂实例,之后获取各种产品对象并调用它们的方法。