python设计模式4:适配器模式

使用适配器模式使用两个或是多个不兼容的接口兼容。在不修改不兼容代码的情况下使用适配器模式实现接口一致性。通过Adapter 类实现。

例子: 一个俱乐部类Club,艺术加被请到俱乐部在表演节目: organize_performance()

Musician类 play() 方法 Dancer 类主要是dance() 方法执行 (external.py

外部模块导入(adapter.py)创建一个通用的 Adapter类调整不兼容的对象。

init() 方法的obj 参数是需要修改的对象,adapted_methods 是一个字典,包含与客户端调用的方法和应该调用方法匹配的键值对。

chapter04/external.py

复制代码
class Musician: 
    def __init__(self, name): 
        self.name = name
 
    def __str__(self): 
        return f'the musician {self.name}' 
 
    def play(self): 
        return 'plays music' 
 
class Dancer: 
    def __init__(self, name): 
        self.name = name 
 
    def __str__(self): 
        return f'the dancer {self.name}' 
 
    def dance(self): 
        return 'does a dance performance' 

chapter04/adapter.py

复制代码
from external import Musician, Dancer

 
class Club: 
    def __init__(self, name): 
        self.name = name 
 
    def __str__(self): 
        return f'the club {self.name}' 
 
    def organize_event(self): 
        return 'hires an artist to perform for the people' 

        
class Adapter: 
    def __init__(self, obj, adapted_methods): 
        self.obj = obj 
        self.__dict__.update(adapted_methods) 
 
    def __str__(self): 
        return str(self.obj) 

        
def main(): 

    objects = [Club('Jazz Cafe'), Musician('Roy Ayers'), Dancer('Shane Sparks')]
    
    for obj in objects:
        if hasattr(obj, 'play') or hasattr(obj, 'dance'):
            if hasattr(obj, 'play'):
                adapted_methods = dict(organize_event=obj.play)   # 设置调用方法统一organize_event
            elif hasattr(obj, 'dance'):            
                adapted_methods = dict(organize_event=obj.dance)    # 设置调用方法统一organize_event
                
            # referencing the adapted object here
            obj = Adapter(obj, adapted_methods)
            
        print(f' 输出 {obj} {obj.organize_event()}')  # 调用统一方法

  
if __name__ == "__main__": 
    main()

输出 the club Jazz Cafe hires an artist to perform for the people

输出 the musician Roy Ayers plays music

输出 the dancer Shane Sparks does a dance performance

相关推荐
Python×CATIA工业智造1 小时前
Frida RPC高级应用:动态模拟执行Android so文件实战指南
开发语言·python·pycharm
onceco2 小时前
领域LLM九讲——第5讲 为什么选择OpenManus而不是QwenAgent(附LLM免费api邀请码)
人工智能·python·深度学习·语言模型·自然语言处理·自动化
狐凄2 小时前
Python实例题:基于 Python 的简单聊天机器人
开发语言·python
悦悦子a啊3 小时前
Python之--基本知识
开发语言·前端·python
缘来是庄4 小时前
设计模式之访问者模式
java·设计模式·访问者模式
笑稀了的野生俊5 小时前
在服务器中下载 HuggingFace 模型:终极指南
linux·服务器·python·bash·gpu算力
Naiva5 小时前
【小技巧】Python+PyCharm IDE 配置解释器出错,环境配置不完整或不兼容。(小智AI、MCP、聚合数据、实时新闻查询、NBA赛事查询)
ide·python·pycharm
路来了5 小时前
Python小工具之PDF合并
开发语言·windows·python
蓝婷儿6 小时前
Python 机器学习核心入门与实战进阶 Day 3 - 决策树 & 随机森林模型实战
人工智能·python·机器学习
AntBlack6 小时前
拖了五个月 ,不当韭菜体验版算是正式发布了
前端·后端·python