一、工厂模式概述
(一)定义
工厂模式是一种创建型设计模式。它的核心思想是定义一个创建对象的接口(可以是抽象类或者接口),让子类决定实例化哪一个类。工厂方法把实例化推迟到子类,这样就可以将对象的创建和使用分离,从而提高系统的灵活性和可扩展性。
(二)分类
- 简单工厂模式
- 这种模式不是严格的设计模式,但它为工厂模式奠定了基础。它由一个工厂类来决定创建哪一种产品类的实例。简单工厂模式的结构相对简单,它包含一个工厂类和多个产品类。
- 例如,假设我们要创建不同类型的图形对象,如圆形、矩形等。简单工厂模式下,有一个图形工厂类,根据传入的参数(如“circle”表示圆形,“rectangle”表示矩形)来创建对应的图形对象。
- 工厂方法模式
- 工厂方法模式是简单工厂模式的升级。它引入了抽象工厂类,这个抽象工厂类声明了一个工厂方法,用于创建产品对象。具体的子类工厂继承抽象工厂类,并实现工厂方法来创建具体的产品对象。
- 以汽车制造为例,有一个抽象的汽车工厂类,它有一个工厂方法用于创建汽车。然后有具体的工厂类,如宝马工厂和奔驰工厂,它们继承抽象工厂类。宝马工厂的工厂方法创建宝马汽车对象,奔驰工厂的工厂方法创建奔驰汽车对象。
- 抽象工厂模式
- 抽象工厂模式是最复杂的工厂模式。它提供了一个接口,用于创建相关或依赖对象的家族,而不需要明确指定具体类。这种模式适用于产品族和产品等级结构都比较复杂的情况。
- 比如,一个电子产品公司生产手机和电脑两种产品,而且有高端和低端两种产品等级。抽象工厂模式下,有一个抽象工厂接口,用于创建手机和电脑。然后有高端产品工厂和低端产品工厂,高端产品工厂创建高端手机和高端电脑,低端产品工厂创建低端手机和低端电脑。
二、Python中实现工厂模式
(一)简单工厂模式
# 定义产品接口
class Shape:
def draw(self):
pass
# 创建具体产品类
class Circle(Shape):
def draw(self):
print("Inside Circle::draw() method.")
class Rectangle(Shape):
def draw(self):
print("Inside Rectangle::draw() method.")
# 创建工厂类
class ShapeFactory:
def get_shape(self, shape_type):
if shape_type == None:
return None
if shape_type == "circle":
return Circle()
elif shape_type == "rectangle":
return Rectangle()
return None
# 使用
shape_factory = ShapeFactory()
shape1 = shape_factory.get_shape("circle")
shape1.draw()
shape2 = shape_factory.get_shape("rectangle")
shape2.draw()
在这个例子中,ShapeFactory类根据传入的shape_type参数来决定创建Circle还是Rectangle对象。
(二)工厂方法模式
# 定义产品接口
class Shape:
def draw(self):
pass
# 创建具体产品类
class Circle(Shape):
def draw(self):
print("Inside Circle::draw() method.")
class Rectangle(Shape):
def draw(self):
print("Inside Rectangle::draw() method.")
# 定义抽象工厂类
class ShapeFactory:
def get_shape(self):
pass
# 创建具体工厂类
class CircleFactory(ShapeFactory):
def get_shape(self):
return Circle()
class RectangleFactory(ShapeFactory):
def get_shape(self):
return Rectangle()
# 使用
circle_factory = CircleFactory()
circle = circle_factory.get_shape()
circle.draw()
rectangle_factory = RectangleFactory()
rectangle = rectangle_factory.get_shape()
rectangle.draw()
这里ShapeFactory是抽象工厂类,CircleFactory和RectangleFactory是具体的工厂类,它们分别实现了get_shape方法来创建对应的Circle和Rectangle对象。
(三)抽象工厂模式
# 定义产品接口
class Shape:
def draw(self):
pass
class Color:
def fill(self):
pass
# 创建具体产品类
class Circle(Shape):
def draw(self):
print("Inside Circle::draw() method.")
class Rectangle(Shape):
def draw(self):
print("Inside Rectangle::draw() method.")
class Red(Color):
def fill(self):
print("Inside Red::fill() method.")
class Blue(Color):
def fill(self):
print("Inside Blue::fill() method.")
# 定义抽象工厂类
class AbstractFactory:
def get_shape(self):
pass
def get_color(self):
pass
# 创建具体工厂类
class ShapeFactory(AbstractFactory):
def get_shape(self):
return Circle()
def get_color(self):
return None
class ColorFactory(AbstractFactory):
def get_shape(self):
return None
def get_color(self):
return Red()
# 使用
shape_factory = ShapeFactory()
shape = shape_factory.get_shape()
shape.draw()
color_factory = ColorFactory()
color = color_factory.get_color()
color.fill()
在这个例子中,AbstractFactory是抽象工厂类,ShapeFactory和ColorFactory是具体工厂类。ShapeFactory创建形状对象,ColorFactory创建颜色对象。这种模式可以很方便地扩展新的产品族和产品等级结构。
三、python中实现策略模式
(一)定义
策略模式(Strategy Pattern) :定义一系列算法(或操作),将每个算法封装起来,并使它们可以互换。Ironic 的每个 interface(如 DeployInterface)就是一个策略,具体的 driver 实现(如 AgentDeploy、PXEDeploy)就是不同的策略实现。
(二)例子
import abc
class DeployInterface(metaclass=abc.ABCMeta):
@abc.abstractmethod
def deploy(self, task):
pass
@abc.abstractmethod
def tear_down(self, task):
pass
class PXEDeploy(DeployInterface):
def deploy(self, task):
print("Deploying node with PXE")
def tear_down(self, task):
print("Tearing down PXE deployment")
class AgentDeploy(DeployInterface):
def deploy(self, task):
print("Deploying node with Agent")
def tear_down(self, task):
print("Tearing down Agent deployment")
def run_deploy(deploy_interface: DeployInterface, task):
deploy_interface.deploy(task)
deploy_interface.tear_down(task)
# 假设根据配置或硬件类型动态选择
deploy_impl = PXEDeploy() # 或 AgentDeploy()
run_deploy(deploy_impl, task={})
# 输出
Deploying node with PXE
Tearing down PXE deployment
四、python中实现观察者模式
1. 概念
观察者模式(Observer Pattern)是一种设计模式,用于实现对象间的一对多依赖关系。当“被观察者”对象状态发生变化时,所有“观察者”对象都会收到通知并自动更新。
常用于事件驱动、消息订阅、GUI、数据同步等场景。
2. 结构
- Subject(被观察者):维护观察者列表,状态变化时通知所有观察者。
- Observer(观察者):定义响应接口,接收通知并处理。
3. Python 实现示例
# 观察者模式简单实现
class Subject:
def __init__(self):
self._observers = []
def attach(self, observer):
self._observers.append(observer)
def detach(self, observer):
self._observers.remove(observer)
def notify(self, message):
for observer in self._observers:
observer.update(message)
class Observer:
def update(self, message):
print(f"Received message: {message}")
# 使用示例
subject = Subject()
observer1 = Observer()
observer2 = Observer()
subject.attach(observer1)
subject.attach(observer2)
subject.notify("Hello Observers!") # 两个观察者都收到通知
4. 应用场景
- 事件系统:如 Django signals、Celery signals
- GUI 框架:按钮点击、窗口变化等
- 数据模型同步:如模型变化通知视图更新
- 消息订阅发布:如 pub/sub 系统