适配器模式

作者: nummycode | 来源:发表于2017-07-06 18:11 被阅读1次

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

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,输出结果为:

winner is cat_a with 40 Km/h
winner is nemo with 60 Km/h

相关文章

  • Java设计模式(二)

    talk is cheap show me the code 适配器模式 类适配器模式 接口适配器模式 对象适配器...

  • 适配器模式

    目录 1、什么是适配器模式? 2、适配器模式结构? 3、如何实现适配器模式? 4、适配器模式的特点? 5、适配器模...

  • 设计模式之适配器模式

    适配器模式: 类适配器模式、对象适配器模式、接口适配器模式 1.类适配器模式:新的接口出现了,但是和老的接口不兼容...

  • 学习iOS设计模式第一章 适配器(Adapter)

    今天学习了iOS设计模式中的适配器模式,适配器有两种模式对象适配器模式-- 在这种适配器模式中,适配器容纳一个它包...

  • 第4章 结构型模式-适配器模式

    一、适配器模式简介 二、适配器模式的优点 三、适配器模式的实例

  • 设计模式(Design Patterns)适配器模式(Adapt

    适配器模式主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。 类的适配器模式 场景:将一个类转换成...

  • 适配器模式

    适配器模式主要分为三类:类的适配器模式、对象的适配器模式、接口的适配器模式。适配器模式将某个类的接口转换成客户端期...

  • 适配器模式

    先直观感受下什么叫适配器 适配器模式有类的适配器模式和对象的适配器模式两种不同的形式。 类适配器模式 对象适配器模...

  • 适配器模式

    适配器模式 一、适配器模式定义 适配器模式的定义是,Convert the interface of a clas...

  • 设计模式:结构型

    享元模式 (Pools,Message) 代理模式 适配器模式 :类适配器和对象适配器 装饰者模式 外观模式 桥接...

网友评论

    本文标题:适配器模式

    本文链接:https://www.haomeiwen.com/subject/blqkhxtx.html