赞
踩

抽象工厂是一种创建型设计模式,主要解决接口选择的问题。能够创建一系列相关的对象,而无需指定其具体类。
系统中有多于一个的产品族,且这些产品族类的产品需实现同样的接口。
例如:有一个家具工厂,可以生产的产品有椅子、沙发、咖啡桌,各产品又分为不同的风格。

而客户需要的是相同风格的各类产品


- __doc__ = """
- 抽象工厂模式
- 例:有一个家具工厂,可以生产的产品有椅子、沙发、咖啡桌,各产品又分为不同的风格。
- """
-
- from abc import ABC, abstractmethod
-
-
- class AbstractFactory(ABC):
- """
- 抽象工厂基类
- 提供创建三种家具抽象方法
- """
-
- @abstractmethod
- def create_chair(self):
- pass
-
- @abstractmethod
- def create_sofa(self):
- pass
-
- @abstractmethod
- def create_coffee_table(self):
- pass
-
-
- class ModernFactory(AbstractFactory):
- """
- 具体工厂基类
- 实现创建现代风格家具的方法
- """
-
- def create_chair(self):
- return ModernChair()
-
- def create_sofa(self):
- return ModernSofa()
-
- def create_coffee_table(self):
- return ModernCoffeeTable()
-
-
- class VictorianFactory(AbstractFactory):
- """
- 具体工厂基类
- 实现创建维多利亚风格家具的方法
- """
-
- def create_chair(self):
- return VictorianChair()
-
- def create_sofa(self):
- return VictorianSofa()
-
- def create_coffee_table(self):
- return VictorianCoffeeTable()
-
-
- class AbstractProduct(ABC):
- """
- 抽象产品基类
- 提供使用抽象方法
- """
-
- @abstractmethod
- def use(self):
- pass
-
-
- class ModernChair(AbstractProduct):
- """具体产品"""
-
- def use(self):
- print("现代风格椅子")
-
-
- class ModernSofa(AbstractProduct):
- """具体产品"""
-
- def use(self):
- print("现代风格沙发")
-
-
- class ModernCoffeeTable(AbstractProduct):
- """具体产品"""
-
- def use(self):
- print("现代风格咖啡桌")
-
-
- class VictorianChair(AbstractProduct):
- """具体产品"""
-
- def use(self):
- print("维多利亚风格椅子")
-
-
- class VictorianSofa(AbstractProduct):
- """具体产品"""
-
- def use(self):
- print("维多利亚风格沙发")
-
-
- class VictorianCoffeeTable(AbstractProduct):
- """具体产品"""
-
- def use(self):
- print("维多利亚风格咖啡桌")
-
-
- def client_code(factory):
- """客户端"""
- chair = factory.create_chair()
- sofa = factory.create_sofa()
- coffee_table = factory.create_coffee_table()
-
- chair.use()
- sofa.use()
- coffee_table.use()
-
-
- if __name__ == '__main__':
- """
- Client: Testing client code with the first factory type:
- 现代风格椅子
- 现代风格沙发
- 现代风格咖啡桌
-
- Client: Testing the same client code with the second factory type:
- 维多利亚风格椅子
- 维多利亚风格沙发
- 维多利亚风格咖啡桌
- """
- print("Client: Testing client code with the first factory type:")
- factory1 = ModernFactory()
- client_code(factory1)
-
- print()
-
- print("Client: Testing the same client code with the second factory type:")
- factory2 = VictorianFactory()
- client_code(factory2)

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。