行为型模式

设计模式教程 · 第 4 章 · 8 次浏览

策略(Strategy)把"一族可互换的算法"封装起来,运行时动态选择:支付方式、运费计算、排序方式。

思想

把变化的部分抽象成接口,每个实现是一个策略。调用方持有策略对象,想换就换,不用改调用代码。

代码示例

# 策略模式:运费计算
class ShippingStrategy:
    def cost(self, weight):
        raise NotImplementedError

class StandardShipping(ShippingStrategy):    # 标准:每公斤 5 元
    def cost(self, weight):
        return weight * 5

class ExpressShipping(ShippingStrategy):     # 快递:每公斤 12 元
    def cost(self, weight):
        return weight * 12

class FreeShipping(ShippingStrategy):        # 满额免邮
    def cost(self, weight):
        return 0

class Order:
    def __init__(self, strategy):
        self.strategy = strategy

    def shipping_cost(self, weight):
        return self.strategy.cost(weight)

# 运行时不换实现
order = Order(ExpressShipping())
print("快递费:", order.shipping_cost(3))    # 36

order.strategy = FreeShipping()              # 换策略
print("免邮费:", order.shipping_cost(3))    # 0
📚 Python 语法速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
写法 / 语法作用
print("hello")输出到控制台
name = "张三"变量赋值(无需声明类型)
if x > 0: ...条件判断(注意冒号和缩进)
for i in range(10): ...循环(缩进是语法的一部分)
while x < 10: ...条件循环
def fn(a, b): return a + b定义函数
class Person: ...定义类
list = [1, 2, 3]列表(可改)
tuple = (1, 2)元组(不可改)
dict = {"key": "value"}字典(键值对)
set = {1, 2, 3}集合(去重)
len(obj)取长度
str(x) / int(x) / float(x)类型转换
s.split(",")字符串按分隔符拆分
" ".join(list)列表拼接成字符串
import os导入模块
from math import sqrt从模块导入指定函数
try: ... except Exception as e: ...异常捕获
with open("a.txt", "r") as f: ...文件读取(自动关闭)
f"你好 {name}"f-string 格式化
lambda x: x * 2匿名函数
list(map(fn, arr))函数式处理列表
range(start, stop, step)生成数字序列
if __name__ == "__main__":主入口判断
pip install 包名安装第三方包(命令行)