news 2026/5/30 12:29:54

Python设计模式:常用模式实战解析

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
Python设计模式:常用模式实战解析

Python设计模式:常用模式实战解析

引言

设计模式是解决常见软件设计问题的通用解决方案。作为一名从Python转向Rust的后端开发者,理解设计模式对于编写可维护、可扩展的代码至关重要。本文将深入探讨Python中常用的设计模式,帮助你在实际项目中应用这些模式。

一、创建型模式

1.1 单例模式

class Singleton: _instance = None def __new__(cls, *args, **kwargs): if cls._instance is None: cls._instance = super().__new__(cls, *args, **kwargs) return cls._instance def __init__(self): if not hasattr(self, 'initialized'): self.value = 0 self.initialized = True s1 = Singleton() s2 = Singleton() print(s1 is s2) # True

1.2 工厂模式

from abc import ABC, abstractmethod class Product(ABC): @abstractmethod def operation(self): pass class ConcreteProductA(Product): def operation(self): return "Product A operation" class ConcreteProductB(Product): def operation(self): return "Product B operation" class Factory: def create_product(self, type_): if type_ == 'A': return ConcreteProductA() elif type_ == 'B': return ConcreteProductB() else: raise ValueError("Unknown product type") factory = Factory() product = factory.create_product('A') print(product.operation())

1.3 建造者模式

class Computer: def __init__(self): self.cpu = None self.ram = None self.storage = None def __str__(self): return f"CPU: {self.cpu}, RAM: {self.ram}, Storage: {self.storage}" class ComputerBuilder: def __init__(self): self.computer = Computer() def set_cpu(self, cpu): self.computer.cpu = cpu return self def set_ram(self, ram): self.computer.ram = ram return self def set_storage(self, storage): self.computer.storage = storage return self def build(self): return self.computer builder = ComputerBuilder() computer = builder.set_cpu('Intel i7').set_ram('16GB').set_storage('1TB').build() print(computer)

二、结构型模式

2.1 适配器模式

class Target: def request(self): return "Target request" class Adaptee: def specific_request(self): return "Specific request" class Adapter(Target): def __init__(self, adaptee): self.adaptee = adaptee def request(self): return f"Adapter: {self.adaptee.specific_request()}" adaptee = Adaptee() adapter = Adapter(adaptee) print(adapter.request())

2.2 装饰器模式

class Component: def operation(self): return "Component operation" class Decorator(Component): def __init__(self, component): self.component = component def operation(self): return f"Decorator: {self.component.operation()}" class ConcreteDecoratorA(Decorator): def operation(self): return f"ConcreteDecoratorA: {self.component.operation()}" component = Component() decorated = ConcreteDecoratorA(component) print(decorated.operation())

2.3 代理模式

class Subject: def request(self): pass class RealSubject(Subject): def request(self): return "RealSubject request" class Proxy(Subject): def __init__(self): self.real_subject = None def request(self): if self.real_subject is None: self.real_subject = RealSubject() return f"Proxy: {self.real_subject.request()}" proxy = Proxy() print(proxy.request())

三、行为型模式

3.1 观察者模式

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): for observer in self.observers: observer.update(self) class ConcreteSubject(Subject): def __init__(self): super().__init__() self.state = 0 def set_state(self, state): self.state = state self.notify() class Observer: def update(self, subject): pass class ConcreteObserverA(Observer): def update(self, subject): print(f"Observer A: State changed to {subject.state}") class ConcreteObserverB(Observer): def update(self, subject): print(f"Observer B: State changed to {subject.state}") subject = ConcreteSubject() observer_a = ConcreteObserverA() observer_b = ConcreteObserverB() subject.attach(observer_a) subject.attach(observer_b) subject.set_state(10)

3.2 策略模式

from abc import ABC, abstractmethod class Strategy(ABC): @abstractmethod def execute(self, data): pass class ConcreteStrategyA(Strategy): def execute(self, data): return sorted(data) class ConcreteStrategyB(Strategy): def execute(self, data): return sorted(data, reverse=True) class Context: def __init__(self, strategy): self.strategy = strategy def set_strategy(self, strategy): self.strategy = strategy def process(self, data): return self.strategy.execute(data) context = Context(ConcreteStrategyA()) print(context.process([3, 1, 4, 1, 5])) context.set_strategy(ConcreteStrategyB()) print(context.process([3, 1, 4, 1, 5]))

3.3 模板方法模式

from abc import ABC, abstractmethod class AbstractClass(ABC): def template_method(self): self.base_operation1() self.required_operation1() self.base_operation2() self.hook() def base_operation1(self): print("Base operation 1") def base_operation2(self): print("Base operation 2") @abstractmethod def required_operation1(self): pass def hook(self): pass class ConcreteClass(AbstractClass): def required_operation1(self): print("Concrete operation 1") def hook(self): print("Optional hook") concrete = ConcreteClass() concrete.template_method()

四、实战案例:设计模式组合应用

4.1 日志系统设计

class Logger: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) cls._instance.handlers = [] return cls._instance def add_handler(self, handler): self.handlers.append(handler) def log(self, message): for handler in self.handlers: handler.handle(message) class Handler: def handle(self, message): pass class ConsoleHandler(Handler): def handle(self, message): print(f"Console: {message}") class FileHandler(Handler): def __init__(self, filename): self.filename = filename def handle(self, message): with open(self.filename, 'a') as f: f.write(f"{message}\n") class FormattingHandler(Handler): def __init__(self, handler, format_): self.handler = handler self.format_ = format_ def handle(self, message): formatted = self.format_.format(message=message) self.handler.handle(formatted) logger = Logger() console = ConsoleHandler() file = FileHandler('app.log') formatted = FormattingHandler(console, "[LOG] {message}") logger.add_handler(formatted) logger.add_handler(file) logger.log("Application started")

4.2 数据处理管道

class Pipeline: def __init__(self): self.steps = [] def add_step(self, step): self.steps.append(step) def process(self, data): result = data for step in self.steps: result = step.execute(result) return result class Step: def execute(self, data): pass class ValidateStep(Step): def execute(self, data): if not data: raise ValueError("Empty data") return data class TransformStep(Step): def __init__(self, func): self.func = func def execute(self, data): return self.func(data) class SaveStep(Step): def execute(self, data): print(f"Saving: {data}") return data pipeline = Pipeline() pipeline.add_step(ValidateStep()) pipeline.add_step(TransformStep(lambda x: x.upper())) pipeline.add_step(SaveStep()) pipeline.process("hello world")

五、设计模式最佳实践

5.1 选择合适的模式

问题类型推荐模式
对象创建工厂模式、建造者模式
对象组合适配器模式、装饰器模式
对象行为观察者模式、策略模式
对象访问代理模式

5.2 避免过度设计

# 不要为简单问题使用复杂模式 # 简单场景:直接创建对象 user = User(name="Alice", age=30) # 复杂场景:使用工厂模式 class UserFactory: @staticmethod def create_admin(name): return User(name=name, role="admin") @staticmethod def create_user(name): return User(name=name, role="user")

5.3 遵循SOLID原则

# 单一职责原则 class UserRepository: def save(self, user): pass class UserService: def __init__(self, repository): self.repository = repository def create_user(self, name): user = User(name=name) self.repository.save(user) return user

六、设计模式与Rust对比

6.1 Python设计模式

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

6.2 Rust设计模式

use std::sync::{Arc, Mutex}; struct Singleton { value: i32, } lazy_static! { static ref INSTANCE: Arc<Mutex<Singleton>> = Arc::new(Mutex::new(Singleton { value: 0 })); } impl Singleton { fn get_instance() -> Arc<Mutex<Self>> { INSTANCE.clone() } }

6.3 对比分析

特性PythonRust
实现复杂度较低较高
线程安全需要手动处理编译时保证
性能有运行时开销零成本抽象
灵活性较高较低

总结

设计模式是编写高质量代码的重要工具。通过本文的学习,你应该掌握了以下核心要点:

  1. 创建型模式:单例模式、工厂模式、建造者模式
  2. 结构型模式:适配器模式、装饰器模式、代理模式
  3. 行为型模式:观察者模式、策略模式、模板方法模式
  4. 实战案例:日志系统、数据处理管道
  5. 最佳实践:选择合适模式、避免过度设计、遵循SOLID原则
  6. 与Rust对比:实现方式和特性差异

作为从Python转向Rust的后端开发者,理解设计模式有助于你在两种语言之间进行有效的思维转换。虽然Rust的类型系统和所有权模型改变了某些模式的实现方式,但核心思想是相通的。

版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/5/30 12:29:16

HAMI-VNPU-软切分:device-plugin

摘要 1、基于 https://github.com/Project-HAMi/ascend-device-plugin/tree/v1.3.0 分析软切分 NPU 的 Device Plugin 代码 2、回答几个问题&#xff1a; 与华为原生的 Device Plugin 有何区别&#xff1a;上报的资源、分配机制&#xff1f; 软切分是如何实现的&#xff1f;简要…

作者头像 李华
网站建设 2026/5/30 12:28:14

从零开始电路设计:原理图到PCB焊接全流程实战指南

1. 项目概述&#xff1a;从纸上谈兵到动手造物电路设计&#xff0c;听起来像是实验室里穿着白大褂的工程师对着电脑屏幕和复杂公式的专属领域。但如果你拆开手边的任何一件电子设备——从最简单的电子闹钟到复杂的智能手机——你会发现&#xff0c;它们的内核都是由一个个微小的…

作者头像 李华
网站建设 2026/5/30 12:26:04

基于Haar级联与造型规则的实时耳饰推荐系统实现

1. 项目概述&#xff1a;一个无需深度学习的实时造型顾问 你有没有过这样的经历&#xff1a;站在镜子前&#xff0c;面对一堆耳饰&#xff0c;却完全不知道哪一款真正适合自己脸型&#xff1f;这几乎是每个人都会遇到的日常困扰。传统的解决方案要么是依赖造型师的经验&#xf…

作者头像 李华