当前位置: 首页 > news >正文

软件设计模式详解

软件设计模式详解

1. 技术分析

1.1 设计模式概述

设计模式是可复用的软件设计方案:

设计模式分类 创建型: 对象创建 结构型: 对象组合 行为型: 对象交互 设计原则: 单一职责 开闭原则 依赖倒置 接口隔离

1.2 创建型模式

创建型模式 Factory Method: 工厂方法 Abstract Factory: 抽象工厂 Builder: 建造者 Prototype: 原型 Singleton: 单例 核心目标: 封装创建逻辑 解耦创建与使用

1.3 结构型模式

结构型模式 Adapter: 适配器 Bridge: 桥接 Composite: 组合 Decorator: 装饰器 Facade: 外观 Flyweight: 享元 Proxy: 代理 核心目标: 优化结构组合 提高复用性

1.4 行为型模式

模式用途特点
Observer发布-订阅松耦合
Strategy算法切换灵活扩展
Command请求封装可撤销
Iterator遍历集合统一接口

2. 核心功能实现

2.1 工厂模式

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(ABC): @abstractmethod def create_product(self): pass class ConcreteFactoryA(Factory): def create_product(self): return ConcreteProductA() class ConcreteFactoryB(Factory): def create_product(self): return ConcreteProductB() # 使用 factory_a = ConcreteFactoryA() product_a = factory_a.create_product() print(product_a.operation())

2.2 单例模式

class Singleton: _instance = None def __new__(cls): if cls._instance is None: cls._instance = super().__new__(cls) return cls._instance def __init__(self): self.counter = 0 def increment(self): self.counter += 1 return self.counter # 使用 s1 = Singleton() s2 = Singleton() print(s1 is s2) # True print(s1.increment()) # 1 print(s2.increment()) # 2

2.3 观察者模式

class Subject: def __init__(self): self._observers = [] def attach(self, observer): if observer not in self._observers: self._observers.append(observer) def detach(self, observer): self._observers.remove(observer) def notify(self, message): for observer in self._observers: observer.update(message) class Observer: def __init__(self, name): self.name = name def update(self, message): print(f"{self.name} received: {message}") # 使用 subject = Subject() observer1 = Observer("Observer 1") observer2 = Observer("Observer 2") subject.attach(observer1) subject.attach(observer2) subject.notify("Hello World!")

2.4 策略模式

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) # 使用 data = [3, 1, 4, 1, 5, 9] context = Context(ConcreteStrategyA()) print(context.process(data)) # [1, 1, 3, 4, 5, 9] context.set_strategy(ConcreteStrategyB()) print(context.process(data)) # [9, 5, 4, 3, 1, 1]

2.5 装饰器模式

class Component: def operation(self): return "Base operation" class Decorator(Component): def __init__(self, component): self._component = component def operation(self): return self._component.operation() class ConcreteDecoratorA(Decorator): def operation(self): return f"Decorator A({self._component.operation()})" class ConcreteDecoratorB(Decorator): def operation(self): return f"Decorator B({self._component.operation()})" # 使用 component = Component() decorated = ConcreteDecoratorA(ConcreteDecoratorB(component)) print(decorated.operation()) # Decorator A(Decorator B(Base operation))

3. 性能对比

3.1 创建型模式对比

模式灵活性复杂度适用场景
Factory Method简单对象创建
Abstract Factory系列产品创建
Builder复杂对象创建
Singleton全局唯一实例

3.2 结构型模式对比

模式解耦程度性能影响适用场景
Adapter接口兼容
Decorator功能增强
Proxy访问控制

3.3 行为型模式对比

模式扩展性复杂度适用场景
Observer事件通知
Strategy算法切换
Command请求封装

4. 最佳实践

4.1 模式选择指南

def choose_pattern(problem): patterns = { 'object_creation': 'Factory Method', 'complex_object': 'Builder', 'global_state': 'Singleton', 'interface_adaptation': 'Adapter', 'dynamic_functionality': 'Decorator', 'event_notification': 'Observer', 'algorithm_variation': 'Strategy' } return patterns.get(problem, 'No pattern recommended')

4.2 设计原则应用

# 单一职责 class UserRepository: def save(self, user): pass class UserValidator: def validate(self, user): pass # 开闭原则 class Shape(ABC): @abstractmethod def area(self): pass class Circle(Shape): def area(self): pass

5. 总结

设计模式是软件开发的宝贵财富:

  1. 创建型:封装对象创建
  2. 结构型:优化类结构
  3. 行为型:协调对象交互
  4. 设计原则:指导模式应用

对比数据如下:

  • 工厂模式最常用
  • 观察者模式适合事件驱动
  • 策略模式提高代码灵活性
  • 推荐根据问题选择合适模式
http://www.jsqmd.com/news/866107/

相关文章:

  • ARM架构TLBIMVA指令原理与应用详解
  • NodeMCU固件烧录终极指南:告别命令行,3分钟完成ESP8266刷机
  • STM32F103C8T6做MODBUS从机,用串口助手读写寄存器保姆级教程(附源码)
  • 博德之门3模组管理器完整指南:如何快速解决模组冲突并提升游戏体验
  • Unity运行时动态加载Prefab避坑指南:Instantiate、PrefabUtility与AssetBundle到底怎么选?
  • 如何解决Upscayl超分辨率处理中的Vulkan内存与队列错误
  • 运维和开发都该会的技能:在CentOS 7/8上快速搞定ncurses-devel安装与基础测试
  • 手持式电波流速仪 超声波多普勒+雷达双技术
  • 实现两台Redlion设备通过OPC UA进行通信
  • 楚荣威汽车装备|2–30吨随车起重运输车 定制化生产基地——从“专汽之都”走出的性价比之选 - 品牌优选官
  • 2026年5月聚焦:为何华莱特喷砂/抛丸机/喷砂房/空压机/除尘设备机械成为中山喷砂房优选 - 2026年企业推荐榜
  • FPGA开发者必看:SRIO协议中的“Hello包”与AXI4-Stream接口,到底怎么用才高效?
  • SP3485电路设计避坑指南:从电源旁路到AB线上下拉,这些细节别忽略
  • 别再死磕focus属性了!UniApp中input自动聚焦的实战踩坑与正确解法
  • 技术人创业最容易犯的错:产品做完了,发现没人需要
  • ANSYS License服务启动失败?手把手教你用netstat和lmtools搞定1055端口占用
  • 2026年隔离变送器知名品牌推荐,稳定可靠高精度首选安徽泰华 - 品牌推荐大师1
  • 量子噪声环境下资源恢复实验与NISQ计算优化
  • Rust对接对象存储实战:从aws-sdk-rust配置到生产级应用
  • AI中的‘空’:从被忽略的零值到关键信息维度
  • 告别debugtbs!手把手教你用Eruda搞定微信浏览器H5页面调试(附完整配置流程)
  • 湖北楚荣威:中国专用汽车之都的随车起重运输车专业制造商——深度解析随州自备吊品牌的发展逻辑与行业价值 - 品牌优选官
  • 2026 西安装修公司哪家好?西安前十强装修公司真实口碑排名 - 科技焦点
  • 河北杭东丝网主营业务解析:应用场景、客户类型及消声器产品表现 - GrowthUME
  • 别再只生成.bin了!深入fromelf:除了转换,还能从.axf里“挖”出哪些宝藏信息?
  • ShawzinBot终极指南:五分钟掌握Warframe MIDI自动演奏技巧
  • AI多模型协同架构:破解单点依赖与技术主权困局
  • 2026芜湖黄金回收怎么选?鸿运名品黄金回收|优选老店|高价变现|省心省力 - 鸿运名品
  • ARM PMUv3性能监控单元架构与多核配置详解
  • FanControl终极配置指南:从崩溃到稳定的完整解决方案