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

相关推荐
啥都想学点9 分钟前
关于制作技术视频讲解的问卷调查
python
喵手9 分钟前
Python爬虫实战:博物馆官网的“展览预告/正在热展”栏目,抓取展览名称、精确展期、具体展厅位置以及票务/预约规则(附CSV导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·博物馆信息采集·采集展览预告/正在热展等·采集数据csv导出
喵手10 分钟前
Python爬虫实战:电商实体消歧完整实战 - 从混乱店铺名到标准化知识库的工程化实现,一文带你搞定!
爬虫·python·算法·爬虫实战·零基础python爬虫教学·同名实体消除·从混乱店铺名到标准化知识库
aluluka19 分钟前
Emacs折腾日记(三十六)——打造个人笔记系统
笔记·python·emacs
黎子越22 分钟前
python相关练习
java·前端·python
小白学大数据29 分钟前
实测数据:多进程、多线程、异步协程爬虫速度对比
开发语言·爬虫·python·php
小鸡吃米…38 分钟前
机器学习 - 精确率与召回率
人工智能·python·机器学习
sonrisa_1 小时前
Python同一类不同方法中变量值的传递
开发语言·windows·python
逻极1 小时前
OpenClaw「Clawdbot/Moltbot」 深入解析:核心架构深度剖析
python·ai·架构·agent·ai编程·moltbot·openclaw
sayang_shao1 小时前
C++ ONNX Runtime 与 Python Ultralytics 库实现 YOLOv8 模型检测的区别
c++·python·yolo