技术文摘
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 项目中,合理应用这些设计模式可以使代码更具可读性、可扩展性和可维护性,提高开发效率和软件质量。
- Python 实现旅游景点信息与评论的获取及词云与数据可视化
- 11 个令人惊叹的 JavaScript 单行代码
- CSS 轻松打造超酷炫转场动画
- 携程酒店 Flutter 性能优化之实践
- 遗留系统服务的拆分策略
- 数据质量的动态探查与前端相关实现
- 前端开发流程的自动化及提效实践
- 并发编程:CompletableFuture 异步编程并非难事
- 本地运用 Docker Compose 和 Nestjs 迅速构建基于 Dapr 的 Redis 发布/订阅分布式应用
- 对线程安全性的独特理解:如此清新脱俗的讲述
- 写出灵活系统竟这般容易!小白也能搞定高级 Java 业务!
- 五类出色的微服务 Java 框架
- 浏览器开发者工具的实用技巧汇总
- Rust备受赞誉,学习之人却为何寥寥?
- 软件设计中缓存的那些事