Python脚本适配器模式解决什么问题

wen 实用脚本 2

本文目录导读:

Python脚本适配器模式解决什么问题

  1. 核心问题
  2. 三个典型场景
  3. 主要优势
  4. Python特别之处

适配器模式主要解决接口不兼容的问题,具体到Python脚本场景,它帮助你让两个本来无法直接配合工作的类或系统协同运行,而无需修改它们的源代码。

核心问题

当你已有的代码(或第三方库)期望调用某个接口,但实际的对象提供了不同接口时,适配器模式就派上用场了。

三个典型场景

第三方库接口差异

# 假设你有一个使用"send_message"方法的系统
class NotificationSystem:
    def notify(self, sender):
        sender.send_message("Hello")
# 但新的第三方库使用不同的方法名
class ThirdPartyEmailService:
    def send_email(self, content):
        print(f"Sending email: {content}")
# 适配器解决这个差异
class EmailAdapter:
    def __init__(self, service):
        self.service = service
    def send_message(self, content):
        self.service.send_email(content)

遗留系统集成

当你需要将旧系统与新系统对接,但不愿或不能修改旧代码时:

# 旧系统
class LegacyLogger:
    def write_log(self, severity, message):
        print(f"[{severity}] {message}")
# 新系统期望的接口
class NewLogger:
    def info(self, msg): pass
    def error(self, msg): pass
    def warn(self, msg): pass
# 适配器让旧系统适配新接口
class LegacyAdapter(NewLogger):
    def __init__(self, legacy):
        self.legacy = legacy
    def info(self, msg):
        self.legacy.write_log("INFO", msg)
    def error(self, msg):
        self.legacy.write_log("ERROR", msg)

数据格式转换

当不同模块使用不同数据结构时:

# 系统A期望的格式
class XMLProcessor:
    def process(self, xml_data):
        print(f"Processing XML: {xml_data}")
# 系统B产生JSON数据
class JSONDataSource:
    def get_data(self):
        return '{"name": "test", "value": 42}'
# 适配器转换格式
class JSONToXMLAdapter:
    def __init__(self, json_source):
        self.json_source = json_source
    def get_xml_data(self):
        import json
        data = json.loads(self.json_source.get_data())
        # 简单的XML转换
        xml = f"<item><name>{data['name']}</name><value>{data['value']}</value></item>"
        return xml

主要优势

  1. 无需修改现有代码 - 符合开闭原则
  2. 提高代码复用性 - 旧组件可以继续使用
  3. 解耦 - 调用方和被调用方不直接依赖
  4. 渐进式迁移 - 可以逐步替换旧系统

Python特别之处

Python的鸭子类型动态特性让适配器实现更加灵活:

  • 不需要严格的接口继承
  • 可以使用__getattr__实现更通用的转发
  • 配合functools可以创建函数适配器

简单说:遇到"对方的方法名/参数/返回值格式和我不匹配"时,适配器模式就是你最好的解决方案。

抱歉,评论功能暂时关闭!