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

相关推荐
干饭高手11 分钟前
Day9,Hot100(图论)
python·leetcode·图论
honghongstand17 分钟前
代码随想录D52-53 图论 Python
开发语言·python·图论
程序媛-徐师姐33 分钟前
基于 Python Django 的校园互助平台(附源码,文档)
开发语言·python·django·校园互助·校园互助平台
大数据追光猿1 小时前
【深度学习】Pytorch项目实战-基于协同过滤实现物品推荐系统
人工智能·pytorch·python·深度学习·ai编程·推荐算法
师范大学生1 小时前
基于CNN的FashionMNIST数据集识别2——模型训练
python·深度学习·cnn
web137656076431 小时前
纯 Python、Django、FastAPI、Flask、Pyramid、Jupyter、dbt 解析和差异分析
python·django·fastapi
大模型铲屎官1 小时前
哈希表入门到精通:从原理到 Python 实现全解析
开发语言·数据结构·python·算法·哈希算法·哈希表
qq4054251972 小时前
基于python的旅客游记和轨迹分析可视化系统设计(新)
开发语言·python
m0_594526302 小时前
基于 PyQt5 实现分组列表滚动吸顶效果
开发语言·python·qt
找了一圈尾巴3 小时前
设计模式-组合模式、模板模式
设计模式·组合模式