设计模式-适配器模式

拈花ヽ惹草 提交于 2020-03-22 17:18:25

适配器:

  定义:可使无直接联系的两个接口或者类能一起工作

  方法:适配器就相当于在运来的基础上增加一层调用关系(封装)。

  其他:实现适配器的方法有很多,比如说继承、多继承。

# 案例1:
import datetime


class AgeCalculator:  # 计算年龄的接口
    def __init__(self, birthday):
        self.year, self.month, self.day = (int(x) for x in birthday.split('-'))

    def calculate_age(self, date):
        year, month, day = (int(x) for x in date.split('-'))
        age = year-self.year
        if (month, day) < (self.month, self.day):
            age -= 1
        return age


class DateAgeAdapter: # 适配器:格式化date,不影响其功能
    def _str_date(self, date):
        return date.strftime("%Y-%m-%d")

    def __init__(self, birthday):
        birthday = self._str_date(birthday)
        self.calculator = AgeCalculator(birthday)

    def get_age(self, date):
        date = self._str_date(date)
        return self.calculator.calculate_age(date)
    
    
# 案例2:使两个不先关的两个类,能一起工作

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 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 Adapter:
    def __init__(self, obj, adapted_methods):
        self.obj = obj
        self.name = obj.name  # 处理类里面的属性
        self.__dict__.update(adapted_methods) # 处理类里面的属性

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

def main():
    objects = [Computer('Asus')]
    synth = Synthesizer('moog')
    objects.append(Adapter(synth, dict(execute=synth.play)))
    for i in objects:
        print('{} {}'.format(str(i), i.execute()))
        print('{}'.format(i.name))
        
if __name__ == '__main__':
    main()
        
结果:
"""
the Asus computer executes a program
Asus
the moog synthesizer is playing an electronic song
moog
"""

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!