Python教程40:常用设计模式

Python教程40:常用设计模式 “不要重复造轮子。” 设计模式是解决常见问题的可复用方案。今天我们学习Python中常用的设计模式,提升代码设计能力。 1. 创建型模式 单例模式(Singleton) 确保类只有一个实例: 1class Singleton: 2 _instance = None 3 4 def __new__(cls): 5 if cls._instance is None: 6 cls._instance = super().__new__(cls) 7 return cls._instance 8 9# 或使用装饰器 10def singleton(cls): 11 instances = {} 12 def get_instance(*args, **kwargs): 13 if cls not in instances: 14 instances[cls] = cls(*args, **kwargs) 15 return instances[cls] 16 return get_instance 17 18@singleton 19class Database: 20 def __init__(self, url): 21 self.url = url 工厂模式(Factory) 根据条件创建不同对象: 1class ShapeFactory: 2 @staticmethod 3 def create_shape(shape_type): 4 if shape_type == "circle": 5 return Circle() 6 elif shape_type == "rectangle": 7 return Rectangle() 8 else: 9 raise ValueError(f"未知形状:{shape_type}") 10 11# 使用 12shape = ShapeFactory.create_shape("circle") 建造者模式(Builder) 分步骤构建复杂对象: 1class QueryBuilder: 2 def __init__(self): 3 self._select = [] 4 self._from = None 5 self._where = [] 6 7 def select(self, *fields): 8 self._select.extend(fields) 9 return self 10 11 def from_table(self, table): 12 self._from = table 13 return self 14 15 def where(self, condition): 16 self._where.append(condition) 17 return self 18 19 def build(self): 20 query = f"SELECT {', '.join(self._select)}" 21 query += f" FROM {self._from}" 22 if self._where: 23 query += f" WHERE {' AND '.join(self._where)}" 24 return query 25 26# 使用(链式调用) 27sql = (QueryBuilder() 28 .select("name", "age") 29 .from_table("users") 30 .where("age > 18") 31 .build()) 2. 结构型模式 适配器模式(Adapter) 使不兼容的接口协同工作: ...

2025-12-11 · 4 min · 658 words · 老墨