设计模式(python实现)--适配器模式(Adapter)

2020-01-26  本文已影响0人  远行_2a22

动机(Motivation)

模式定义

将一个类的接口转换成客户希望的另一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
——《设计模式》GoF

要点总结

UML

例子

例子中多个类有功能类似的接口,当想要用一个接口统一访问,而又无法或者很难修改源码的时候,可以使用适配器模式。

# -*- coding:utf-8 -*-

class Synthesizer:

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

    def __str__(self):
        return 'the {} synthesizer'.format(self.name)

    def play(self):
        return 'is playing an electronic song'


class Human:

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

    def __str__(self):
        return '{} the human'.format(self.name)

    def speak(self):
        return 'says hello'

class Computer:

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

    def __str__(self):
        return 'the {} computer'.format(self.name)

    def execute(self):
        return 'executes a program'


class Adapter:

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

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


if __name__ == '__main__':
    objects = [Computer('Asus')]
    synth = Synthesizer('moog')
    objects.append(Adapter(synth, dict(execute=synth.play)))
    human = Human('Bob')
    objects.append(Adapter(human, dict(execute=human.speak)))

    for i in objects:
        print('{} {}'.format(str(i), i.execute()))

Adapterself.__dict__.update(adapted_methods),其实相当于

class Adapter:
    def __init__(self, obj, adapted_methods):
        self.obj = obj
        self.execute = adapted_methods

if __name__ == '__main__':
  objects.append(Adapter(synth, synth.play))

self.__dict__详细用法可以参考python中的dict

上一篇下一篇

猜你喜欢

热点阅读