技术文摘
Python 中外观模式、桥接模式、组合模式与享元模式的实现
2024-12-30 17:31:36 小编
Python 中外观模式、桥接模式、组合模式与享元模式的实现
在 Python 编程中,设计模式是提高代码质量和可维护性的重要工具。本文将探讨外观模式、桥接模式、组合模式与享元模式的实现。
外观模式提供了一个统一的接口,用于访问子系统中的一群接口。它简化了复杂系统的使用,减少了客户端与众多子系统之间的复杂交互。
class SubsystemA:
def operation_a(self):
print("Subsystem A operation")
class SubsystemB:
def operation_b(self):
print("Subsystem B operation")
class Facade:
def __init__(self):
self.subsystem_a = SubsystemA()
self.subsystem_b = SubsystemB()
def operation(self):
self.subsystem_a.operation_a()
self.subsystem_b.operation_b()
桥接模式将抽象部分与实现部分分离,使它们可以独立地变化。这有助于应对系统中多维度的变化。
class Implementor:
def operation_implement(self):
pass
class ConcreteImplementorA(Implementor):
def operation_implement(self):
print("Concrete Implementor A")
class ConcreteImplementorB(Implementor):
def operation_implement(self):
print("Concrete Implementor B")
class Abstraction:
def __init__(self, implementor):
self.implementor = implementor
def operation(self):
self.implementor.operation_implement()
组合模式允许将对象组合成树形结构以表示“部分-整体”的层次结构。客户对单个对象和组合对象的使用具有一致性。
class Component:
def operation(self):
pass
class Leaf(Component):
def operation(self):
print("Leaf operation")
class Composite(Component):
def __init__(self):
self.children = []
def add(self, component):
self.children.append(component)
def operation(self):
for child in self.children:
child.operation()
享元模式旨在共享重复的对象以减少内存使用和提高性能。
class Flyweight:
def __init__(self, intrinsic_state):
self.intrinsic_state = intrinsic_state
def operation(self, extrinsic_state):
print(f"Intrinsic: {self.intrinsic_state}, Extrinsic: {extrinsic_state}")
class FlyweightFactory:
flyweights = {}
def get_flyweight(self, key):
if key not in self.flyweights:
self.flyweights[key] = Flyweight(key)
return self.flyweights[key]
在实际的 Python 项目中,合理应用这些设计模式可以使代码更具可读性、可扩展性和可维护性,提高开发效率和软件质量。
- Go 技术一面的常见考点有哪些
- 他人 API 调试的一般步骤是什么?
- Java 开发人员必知的地域分布数据库
- Windows 环境下运行 Redis6.x 的编译实战指南
- 15 个使用 React Testing Library 的常见错误
- 以下八个流行的 Python 可视化工具包,你钟爱哪一个?
- 英伟达架构师团队撰文详解:CUDA 编程模型改变,Hopper 缘何如此牛?
- 微前端到底是什么?微前端核心技术大揭秘
- Vue.js 设计与实现:框架设计核心要素解析
- 数据架构中的数据网格架构模式
- 读懂 React Context 源码,掌握绕过 Provider 修改的方法
- Elasticsearch 术语及部署架构解析
- Web 框架的问题解决之道
- Vue2 响应式系统的深度剖析与完善
- C#:基于.NET Core3.1的开源项目助你精通 WPF 框架 Prism