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

相关推荐
Wpa.wk18 分钟前
自动化测试(java) - PO模式了解
java·开发语言·python·测试工具·自动化·po模式
会员果汁18 分钟前
4.设计模式-代理模式
设计模式·代理模式
徐先生 @_@|||20 分钟前
Java/Maven 对比 Python/PyPI
开发语言·python
嘻嘻嘻开心29 分钟前
Collection接口
linux·windows·python
rebekk32 分钟前
什么时候会用到python -m
python
是喵斯特ya1 小时前
python开发web暴力破解工具(进阶篇 包含验证码识别和token的处理)
开发语言·python·web安全
长安牧笛1 小时前
职业技能学习路径规划工具,用户输入目标岗位,如AI工程师,结合现有技能水平,推荐分阶段学习资源(课程/书籍/项目),设置学习进度提醒。
python
长安牧笛1 小时前
智能衣柜—穿搭助手,内置温湿度传感器,潮湿天气启动除湿功能,防止衣服发霉,APP还能记录衣服穿着频率,推荐久没穿的衣服,避免穿搭重复。
python
有一个好名字1 小时前
设计模式-代理模式
java·设计模式·代理模式
free-elcmacom1 小时前
机器学习高阶教程<8>分布式训练三大核心策略拆解
人工智能·分布式·python·机器学习