抽象工厂模式学习笔记
什么是抽象工厂模式
抽象工厂模式是一种创建型设计模式,它提供了一种方法来封装一组相关或相互依赖的对象的创建过程,而不需要指定它们的具体类。
在实际开发中,我们经常需要创建一系列相关的对象,例如同属于某一类产品族的不同类型产品。传统的工厂模式只能创建单一类型的产品,而抽象工厂模式则可以创建不同类型的产品族。
抽象工厂模式的结构
抽象工厂模式包含以下组成部分:
- 抽象工厂(Abstract Factory):定义工厂的基本行为,负责创建一组相关的产品。
- 具体工厂(Concrete Factory):实现抽象工厂中的方法,用于创建具体的产品。
- 抽象产品(Abstract Product):定义产品的共性,描述产品的基本特征和行为。
- 具体产品(Concrete Product):实现抽象产品中定义的方法,由具体工厂创建,与具体工厂相互依赖。
抽象工厂模式的实例
假设我们正在开发一款电子产品商城,其中包括手机和电脑两类产品。手机和电脑都有品牌、型号等属性,并且都需要提供操作系统(Os)和CPU型号(Cpu)等详细信息,但手机和电脑之间又有一些不同的属性。我们可以使用抽象工厂模式来创建两个不同的工厂,分别生产手机和电脑,每个工厂内部再负责生产不同品牌的手机或电脑。
pythonCopy Code# 抽象工厂
class ComputerFactory:
def create_product(self, brand, model, os, cpu):
pass
# 具体工厂
class DellFactory(ComputerFactory):
def create_product(self, brand, model, os, cpu):
return DellComputer(brand, model, os, cpu)
class LenovoFactory(ComputerFactory):
def create_product(self, brand, model, os, cpu):
return LenovoComputer(brand, model, os, cpu)
# 抽象产品
class Computer:
def __init__(self, brand, model, os, cpu):
self.brand = brand
self.model = model
self.os = os
self.cpu = cpu
# 具体产品
class DellComputer(Computer):
pass
class LenovoComputer(Computer):
pass
以上是一个简单的例子,其中我们定义了一个抽象工厂ComputerFactory
和两个具体工厂DellFactory
和LenovoFactory
,它们都实现了create_product
方法用于创建电脑产品。每个工厂内部通过调用不同的构造函数创建具体的产品,即DellComputer
和LenovoComputer
。