Python 设计模式:单例、工厂、观察者、策略、装饰器模式实战

小飞兽 Python 13 次阅读 2026-07-24

Introduction

设计模式是软件工程的结晶。本文用 Python 代码讲解 GOF 23 种模式中最高频的 10 种:单例、工厂方法、抽象工厂、建造者、原型、观察者、策略、装饰器、适配器、迭代器模式的原理和代码示例。

---

单例模式(Singleton)

class Singleton:
    _instance = None
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance.value = 0
        return cls._instance

s1 = Singleton()
s2 = Singleton()
print(s1 is s2)  # True

工厂模式(Factory)

from abc import ABC, abstractmethod

class Shape(ABC):
    @abstractmethod
    def draw(self): pass

class Circle(Shape):
    def draw(self): print("画圆")

class Square(Shape):
    def draw(self): print("画方")

class ShapeFactory:
    @staticmethod
    def create(shape_type):
        shapes = {'circle': Circle, 'square': Square}
        return shapes[shape_type]() if shape_type in shapes else None

factory = ShapeFactory()
shape = factory.create('circle')
shape.draw()

观察者模式(Observer)

class Subject:
    def __init__(self):
        self.observers = []
    def attach(self, obs):
        self.observers.append(obs)
    def detach(self, obs):
        self.observers.remove(obs)
    def notify(self, msg):
        for obs in self.observers:
            obs.update(msg)

class Observer:
    def __init__(self, name): self.name = name
    def update(self, msg):
        print(f"{self.name} 收到: {msg}")

subject = Subject()
subject.attach(Observer("观察者A"))
subject.attach(Observer("观察者B"))
subject.notify("事件发生了!")

策略模式(Strategy)

class PaymentStrategy(ABC):
    @abstractmethod
    def pay(self, amount): pass

class Alipay(PaymentStrategy):
    def pay(self, amount): print(f"支付宝支付 {amount} 元")

class WechatPay(PaymentStrategy):
    def pay(self, amount): print(f"微信支付 {amount} 元")

class Order:
    def __init__(self, payment: PaymentStrategy):
        self.payment = payment
    def checkout(self, amount):
        self.payment.pay(amount)

Order(Alipay()).checkout(299)
Order(WechatPay()).checkout(199)

装饰器模式(Decorator)

class Coffee:
    def cost(self): return 5
    def description(self): return "咖啡"

class Milk(Coffee):
    def __init__(self, coffee): self.coffee = coffee
    def cost(self): return self.coffee.cost() + 2
    def description(self): return self.coffee.description() + " + 牛奶"

class Sugar(Coffee):
    def __init__(self, coffee): self.coffee = coffee
    def cost(self): return self.coffee.cost() + 1
    def description(self): return self.coffee.description() + " + 糖"

coffee = Sugar(Milk(Coffee()))
print(coffee.description(), coffee.cost())  # 咖啡 + 牛奶 + 糖 8

常见问题

Q1: 装饰器模式和之前学的 @decorator 语法有什么关系?Python 的 @语法糖就是装饰器模式的实现,上面 Coffee 类的 Milk/Sugar 是手动装饰器模式。

Q2: 单例模式什么场景用?数据库连接池、配置管理器、日志实例。Python 模块导入天然单例,直接 import 就行。

Q3: 观察者模式和事件总线区别?观察者模式是一对一或一对多;事件总线(EventBus)是多对多,更松耦合,适合大型应用。

延伸阅读

  • 其他 13 种 GOF 模式
  • Python asyncio 事件驱动架构
  • 函数式设计模式

---

作者:小马 | 绍大技术网 shaoda.net