定义
提供一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。
模式结构
AbstractFactory 声明一个创建抽象产品对象的操作接口
ConcreteFactory 实现创建具体产品对象的操作
AbstractProduct 为一类产品对象声明一个接口
ConcreteProduct 定义一个被相应的具体工厂创建的产品对象,实现 AbstractProduct 接口
模式分析
抽象工厂允许客户使用抽象的接口来创建一组相关的产品,而不需要知道实际产出的具体产品是什么,这样,客户就从具体的产品中被解耦。
代码实现
class AbstractPizzaIngredientFactory(object):
def create_dough(self):
raise NotImplementError
def create_sauce(self):
raise NotImplementError
def create_cheese(self):
raise NotImplementError
class NYPizzaIngredientFactory(AbstractPizzaIngredientFactory):
def create_dough(self):
return 'NYDough'
def create_sauce(self):
return 'NYSauce'
def create_cheese(self):
return 'NYCheese'
class AbstractPizza(object):
name = None
dough = None
sauce = None
cheese = None
def prepare(self):
raise NotImplementError
class ChessPizza(AbstractPizza):
def __init__(self, ingredient_factory):
self.ingredient_factory = ingredient_factory
def prepare(self):
self.dough = self.ingredient_factory.create_dough()
self.sauce = self.ingredient_factory.create_sauce()
self.cheese = self.ingredient_factory.create_cheese()
class ClamPizza(AbstractPizza):
def __init__(self, ingredient_factory):
self.ingredient_factory = ingredient_factory
def prepare(self):
self.dough = self.ingredient_factory.create_dough()
self.sauce = self.ingredient_factory.create_sauce()
self.cheese = self.ingredient_factory.create_cheese()
self.calm = self.ingredient_factory.create_calm()
def create_pizza(type):
pizza_ingredient_factory = NYPizzaIngredientFactory()
if type == 'cheese':
pizza = ChessPizza(pizza_ingredient_factory)
else:
pizza = ClamPizza(pizza_ingredient_factory)
return pizza
适用性
- 一个系统要独立于它的产品的创建、组合和表示时
- 一个系统要由多个产品系列中的一个来配置时
- 当要强调一些列相关的产品对象的设计以便进行联合使用时
- 当提供一个产品类库,只想显示它们的接口而不是实现时