设计模式概述
High Contrast
Dark Mode
Light Mode
Sepia
Forest
7 min read1,367 words

设计模式概述

欢迎来到《Python设计模式实战指南》!本章将帮助你建立对设计模式的全面认识,为后续学习打下坚实基础。

什么是设计模式?

设计模式(Design Pattern)是一套被反复使用、多数人知晓、经过分类编目的、代码设计经验的总结。它们不是具体的代码,而是解决特定软件设计问题的通用方案。

graph TB A[设计模式] --> B[被反复验证] A --> C[解决常见问题] A --> D[可复用的解决方案] A --> E[代码设计经验的总结] B --> B1[经过时间检验] C --> C1[标准化解决方案] D --> D1[跨项目应用] E --> E1[最佳实践] style A fill:#ede7f6,stroke:#5e35b1,stroke-width:3px style B fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style C fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style D fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style E fill:#e3f2fd,stroke:#1976d2,stroke-width:2px

设计模式的核心特征

特征 说明
抽象性 模式不是具体代码,而是设计思路
可复用性 同一模式可应用于不同场景
通用性 解决的是共性问题,而非特定问题
标准化 统一的命名和结构,便于沟通

设计模式的起源

设计模式的概念起源于建筑学,由建筑师 Christopher Alexander 在20世纪70年代提出。他发现建筑中有许多重复出现的设计问题,这些问题都有类似的解决方案。

1994年,四位软件工程专家(GoF:Gang of Four)将这个思想引入软件领域,出版了《设计模式:可复用面向对象软件的基础》,确立了23种经典设计模式。

graph LR A[1977年] --> B[建筑学领域] B --> C[Christopher Alexander
提出设计模式概念] C --> D[1994年] D --> E[软件领域] E --> F[GoF四人组
出版《设计模式》] F --> G[确立23种经典模式] style A fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style B fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style C fill:#fff9c4,stroke:#f9a825,stroke-width:2px style D fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style E fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style F fill:#fff9c4,stroke:#f9a825,stroke-width:2px style G fill:#c8e6c9,stroke:#43a047,stroke-width:3px

设计模式的分类

GoF 的23种设计模式按照目的分为三大类:

创建型模式(5种)

解决对象创建相关的问题,使对象的创建和使用分离。

graph LR A[创建型模式] --> B[单例模式] A --> C[工厂方法模式] A --> D[抽象工厂模式] A --> E[建造者模式] A --> F[原型模式] style A fill:#ede7f6,stroke:#5e35b1,stroke-width:3px style B fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style C fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style D fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style E fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style F fill:#e3f2fd,stroke:#1976d2,stroke-width:2px

结构型模式(7种)

解决类和对象组合的问题,通过继承或组合构建更大的结构。

graph LR A[结构型模式] --> B[适配器模式] A --> C[装饰器模式] A --> D[代理模式] A --> E[外观模式] A --> F[桥接模式] A --> G[组合模式] A --> H[享元模式] style A fill:#ede7f6,stroke:#5e35b1,stroke-width:3px style B fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style C fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style D fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style E fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style F fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style G fill:#e3f2fd,stroke:#1976d2,stroke-width:2px style H fill:#e3f2fd,stroke:#1976d2,stroke-width:2px

行为型模式(11种)

解决对象间通信和职责分配的问题,关注对象之间的交互。

graph LR A[行为型模式] --> B[观察者模式] A --> C[策略模式] A --> D[模板方法模式] A --> E[命令模式] A --> F[迭代器模式] A --> G[状态模式] A --> H[责任链模式] A --> I[中介者模式] A --> J[备忘录模式] A --> K[访问者模式] A --> L[解释器模式] style A fill:#ede7f6,stroke:#5e35b1,stroke-width:3px

为什么要学习设计模式?

1. 提高代码质量

# ❌ 没有使用设计模式的代码
class DataProcessor:
def process_csv(self, data):
print(f"处理CSV: {data}")
def process_json(self, data):
print(f"处理JSON: {data}")
def process_xml(self, data):
print(f"处理XML: {data}")
def process_yaml(self, data):
print(f"处理YAML: {data}")
# 每次新增格式都要修改这个类,违反开闭原则
# ✅ 使用策略模式重构
from abc import ABC, abstractmethod
class DataProcessorStrategy(ABC):
@abstractmethod
def process(self, data):
pass
class CSVProcessor(DataProcessorStrategy):
def process(self, data):
return f"处理CSV: {data}"
class JSONProcessor(DataProcessorStrategy):
def process(self, data):
return f"处理JSON: {data}"
# 新增格式只需添加新类,无需修改现有代码
class YAMLProcessor(DataProcessorStrategy):
def process(self, data):
return f"处理YAML: {data}"
class DataProcessor:
def __init__(self, processor: DataProcessorStrategy):
self.processor = processor
def process(self, data):
return self.processor.process(data)

2. 提升沟通效率

当你说"这里可以用单例模式",所有了解设计模式的同事都能立即理解你的意图:

3. 提升架构能力

层级 能力 设计模式的作用
编码 写出能运行的代码 基础语法和逻辑
设计 写出易维护的代码 模式、原则、重构
架构 设计可扩展的系统 模式组合、架构模式

设计模式是从"会写代码"到"会设计系统"的关键一步。

4. 应对面试和工作

面试高频考点: - 大厂面试必问设计模式 - 考察代码质量和架构思维 - 判断候选人的工程素养

实际工作价值: - 快速理解他人代码 - 参与开源项目的门槛 - 代码评审的专业性

设计模式的常见误区

❌ 误区1:设计模式就是死记硬背

错误认识:把23种模式背下来就会用设计模式了。

正确理解:设计模式是一种思维方式,关键是理解"何时用"和"为什么用",而不是"怎么写"。

❌ 误区2:设计模式会让代码变复杂

错误认识:为了用模式而用模式,过度设计。

正确理解:设计模式是为了简化问题,如果用了模式反而更复杂,说明用错了。

# ❌ 过度设计的例子
class SingletonPattern:
_instance = None
_lock = threading.Lock()
def __new__(cls, *args, **kwargs):
if not cls._instance:
with cls._lock:
if not cls._instance:
cls._instance = super().__new__(cls, *args, **kwargs)
return cls._instance
# 只为了打印一句话就用单例模式,过度设计
class Printer(SingletonPattern):
def print(self, text):
print(text)
# ✅ 简单的解决方案
class Printer:
def print(self, text):
print(text)
printer = Printer()
printer.print("Hello")

❌ 误区3:设计模式是万能的

错误认识:所有问题都能用设计模式解决。

正确理解: - 设计模式是工具,不是万能药 - 简单问题不需要复杂方案 - KISS原则(Keep It Simple, Stupid)

设计模式 vs 算法

维度 设计模式 算法
目的 组织代码结构 解决计算问题
关注点 可维护性、可扩展性 正确性、效率
时间复杂度 不涉及 核心指标
复用性 设计思路复用 代码片段复用
例子 单例、工厂、观察者 排序、搜索、动态规划

Python与设计模式

Python语言的特殊性

Python 是一门动态语言,这为设计模式的应用带来了一些特殊性:

# Python的鸭子类型让某些模式变得简单
# 传统语言需要接口,Python不需要
# ❌ Java风格(需要接口)
interface IProcessor {
void process(String data);
}
class CSVProcessor implements IProcessor {
public void process(String data) {
System.out.println("CSV");
}
}
# ✅ Python风格(鸭子类型)
class CSVProcessor:
def process(self, data):
print(f"CSV: {data}")
class JSONProcessor:
def process(self, data):
print(f"JSON: {data}")
# 直接传递,无需接口
def use_processor(processor, data):
processor.process(data)
csv_proc = CSVProcessor()
use_processor(csv_proc, "data")  # 正常工作

Python中的装饰器模式

Python 的 @decorator 语法本身就是装饰器模式的完美实现:

def log_calls(func):
"""装饰器:记录函数调用"""
def wrapper(*args, **kwargs):
print(f"调用 {func.__name__}")
result = func(*args, **kwargs)
print(f"{func.__name__} 完成")
return result
return wrapper
@log_calls
def calculate(x, y):
return x + y
# 等价于 calculate = log_calls(calculate)
calculate(1, 2)

本书的模式选择

GoF 的23种模式中,本书重点讲解15种最常用的核心模式

类型 包含的模式 说明
创建型 4种 单例、工厂方法、建造者、抽象工厂
结构型 5种 适配器、装饰器、代理、外观、组合
行为型 6种 观察者、策略、模板方法、命令、迭代器、状态

选择这些模式是因为: - ✅ 实际开发中最常用 - ✅ 最能体现设计模式的价值 - ✅ 学习价值高

本章要点


下一步面向对象基础 🚀