前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >适配器模式

适配器模式

作者头像
用户2936342
发布2018-08-27 14:09:27
1840
发布2018-08-27 14:09:27
举报
文章被收录于专栏:nummynummy

在计算机编程中,适配器模式(有时候也称包装样式或者包装)将一个类的接口适配成用户所期待的。一个适配允许通常因为接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。

代码语言:javascript
复制
def running_competition(*list_of_animals):
    if len(list_of_animals)<1:
        print("No one Running")
        return
    fastest_animal = list_of_animals[0]
    maxspeed = fastest_animal.running_speed()
    for animal in list_of_animals[1:]:
        runspeed =  animal.running_speed()
        if runspeed > maxspeed:
            fastest_animal = animal
            maxspeed = runspeed
    print("winner is {0} with {1} Km/h".format(fastest_animal.name,maxspeed))


class Cat(object):
    def __init__(self, name, legs):
        self.name = name
        self.legs = legs

    def running_speed(self,):
        if self.legs>4 :
            return 20
        else:
            return 40

running_competition(Cat('cat_a',4),Cat('cat_b',3))


class Fish(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def swim_speed(self):
        if self.age < 2:
            return 40
        else:
            return 60

# to let our fish to participate in tournament it should have similar interface as
# cat, we can also do this by using an adaptor class RunningFish
class RunningFish(object):
    def __init__(self, fish):
        self.legs = 4 # dummy
        self.fish = fish

    def running_speed(self):
        return self.fish.swim_speed()
        
    def __getattr__(self, attr):
        return getattr(self.fish,attr)

running_competition(Cat('cat_a',4),
                    Cat('cat_b',3),
                    RunningFish(Fish('nemo',3)),
                    RunningFish(Fish('dollar',1)))

上面的例子中,Fish的并不具有running_speed()方法,所以添加适配器类RunningFish,输出结果为:

代码语言:javascript
复制
winner is cat_a with 40 Km/h
winner is nemo with 60 Km/h
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017.07.06 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档