适配器模式

 

声明:原文链接:http://www.imooc.com/article/5137

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

 

计算年龄的例子

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime


class AgeCalculator(object):
    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(object):
    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)
        print(self.calculator.calculate_age(date))

if __name__ == '__main__':
    
    birthdate = datetime.date(1982, 3, 25)
    calcudate = datetime.date(2016, 11, 8)
    adapter = DateAgeAdapter(birthdate)
    adapter.get_age(calcudate)

 



 

posted @ 2016-11-08 11:40  我当道士那儿些年  阅读(141)  评论(0编辑  收藏  举报