Python 设计模式 - 适配器模式

2023-11-02

精通Python设计模式第二版 第 4 章 适配器模式 学习笔记

适配器模式

适配器模式是一种结构型设计模式,能帮助我们使两个不兼容的接口兼容。
假设我们想使用function_a()作为接口,但是只有function_b(),则可以使用适配器将function_b()转换(适配)为function_a()

实现

假设我们有这样一个需求:一个俱乐部活动,主要是通过聘请有才华的艺术家,组织演出和活动,来为客户提供娱乐活动

1. 定义Club类

organize_performance()方法是俱乐部可以执行的主要操作

class Club():
    """
    Club :

    Attributes:

    """

    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'

2. 定义Musician类和Dance类

在Musician类中,主要动作有play()方法执行。在Dance类中,主要动作有dance()方法执行

class Musician():
    """
    Musician :

    Attributes:

    """

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f'the musician {self.name}'

    def play(self):
        return 'plays music'


class Dancer():
    """
    Dancer :

    Attributes:

    """

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f'the dancer {self.name}'

    def dance(self):
        return 'does a dance performance'

3. 定义适配器

它允许我们将具有不同接口的许多对象调整为一个统一的接口
adapted_method是一个字典,它包含与客户端调用的方法匹配的键值对

class Adapter():
    """
    Adapter :

    Attributes:

    """

    def __init__(self, obj, adapted_methods):
        self.obj = obj
        self.__dict__.update(adapted_methods)

    def __str__(self):
        return str(self.obj)

4. 调用

当处理不同的类实例是,有如下两种情况

  • 属于Club类的兼容对象不需要调整,我们可以直接使用它
  • 首先需要使用Adapter类调整不兼容的对象
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)
            elif hasattr(obj, 'dance'):
                adapted_methods = dict(organize_event=obj.dance)
            # 此处指被适配的对象
            obj = Adapter(obj, adapted_methods)
        print(f'{obj} {obj.organize_event()}')


获得打印如下

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

完整代码如下


class Club():
    """
    Club :

    Attributes:

    """

    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 Musician():
    """
    Musician :

    Attributes:

    """

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f'the musician {self.name}'

    def play(self):
        return 'plays music'


class Dancer():
    """
    Dancer :

    Attributes:

    """

    def __init__(self, name):
        self.name = name

    def __str__(self):
        return f'the dancer {self.name}'

    def dance(self):
        return 'does a dance performance'


class Adapter():
    """
    Adapter :

    Attributes:

    """

    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)
            elif hasattr(obj, 'dance'):
                adapted_methods = dict(organize_event=obj.dance)
            # 此处指被适配的对象
            obj = Adapter(obj, adapted_methods)
        print(f'{obj} {obj.organize_event()}')


if __name__ == '__main__':
    main()

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Python 设计模式 - 适配器模式 的相关文章

随机推荐