首页 > 其他 > 详细

适配器模式

时间:2016-11-08 13:59:04      阅读:143      评论:0      收藏:0      [点我收藏+]

 

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

 



 

适配器模式

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!