码迷,mamicode.com
首页 > 其他好文 > 详细

适配器模式

时间:2016-11-08 14:00:37      阅读:208      评论:0      收藏:0      [点我收藏+]

标签:get   http   不兼容   strftime   sel   bsp   tor   ret   www   

 

声明:原文链接: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)

 



 

适配器模式

标签:get   http   不兼容   strftime   sel   bsp   tor   ret   www   

原文地址:http://www.cnblogs.com/renfanzi/p/6042412.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!