技术文摘
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 项目中,合理应用这些设计模式可以使代码更具可读性、可扩展性和可维护性,提高开发效率和软件质量。
- 哪种异步编程模式是你的专长?
- MQ 消息乱序引发的业务故障现场
- 三分钟掌握消息队列实践
- C#中文件拷贝的多种方式
- 热门前端框架:公然挑战 Vue、React,斩获 5k star
- 可伸缩架构实例:面对海量数据,怎样实现数据库无限扩展?
- 详解 Autowired 注解,精彩!
- 探索 Python 开发神器:Bpython 的魅力及应用
- Rust 开发常用插件知多少?
- 打造优质 Vue 组件库的清单在此
- Python 可视化之 Plotly 库基础使用
- 探索 PyCuda:借 GPU 加速计算 提高数据处理效率
- 基于 API 的基础架构的三种发布策略
- App 服务端架构的改造升级历程
- 停机部署、蓝绿部署、滚动部署与金丝雀部署的情感纠葛