技术文摘
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 项目中,合理应用这些设计模式可以使代码更具可读性、可扩展性和可维护性,提高开发效率和软件质量。
- React Umi 的国际化配置之道
- ThinkPHP 中泛域名部署的实现途径
- Vue 项目在 Nginx 部署后无法访问后端接口的解决方案
- Vue 中 @click.stop 与 @click.prevent 实例深度剖析
- 正则表达式(regex)简介及基本用法总结
- VSCode 中多行正则表达式匹配实战案例
- Vue 中判断内容滑动到底部的三种方法
- Git 回退到指定版本的三种方法与常见错误
- Javascript + CSS 实现网页拖曳盒子指南:让页面动起来
- ApacheBeam 中延迟数据的处理办法
- vscode 借助 remote-ssh 实现服务器免密连接
- VSCode 远程 XHR 连接失败的问题与解决办法
- PHP 中数据库的安装及数据初始化方法
- Postman 模拟浏览器 HTTP 请求及返回数据详解
- Idea 中 git 查看历史版本的操作方法