结构型模式 - 适配器模式

2018-09-09  本文已影响0人  千反田爱瑠爱好者
  1. 将一个类的接口转换成另外一个接口,使得原本由于接口不兼容而不能一起工作的那些类可以一起工作;
  2. 当希望复用一些现存的类,但是接口又与复用环境要求不一致时适用。

class Player():  # 球员类
    name = None

    def __init__(self, name):
        self.name = name

    def Attack(self):
        pass

    def Defense(self):
        pass


class Forwards(Player):  # 前锋
    def __init__(self, name):
        Player.__init__(self, name)

    def Attack(self):
        print("前锋%s 进攻" % self.name)

    def Defense(self):
        print("前锋%s 防守" % self.name)


class Center(Player):  # 中锋
    def __init__(self, name):
        Player.__init__(self, name)

    def Attack(self):
        print("中锋%s 进攻" % self.name)

    def Defense(self):
        print("中锋%s 防守" % self.name)


class Guards(Player):  # 后卫
    def __init__(self, name):
        Player.__init__(self, name)

    def Attack(self):
        print("后卫%s 进攻" % self.name)

    def Defense(self):
        print("后卫%s 防守" % self.name)


class ForeignCenter(Player):  # 外籍中锋(待适配类)
    name = ''

    def __init__(self, name):
        Player.__init__(self, name)

    def ForeignAttack(self):
        print("外籍中锋%s 进攻" % self.name)

    def ForeignDefense(self):
        print("外籍中锋%s 防守" % self.name)


class Translator(Player):  # 翻译(适配类,使外籍中锋都可以使用’Attack‘)
    foreignCenter = None

    def __init__(self, name):
        super().__init__(name)
        self.foreignCenter = ForeignCenter(name)

    def Attack(self):
        self.foreignCenter.ForeignAttack()

    def Defense(self):
        self.foreignCenter.ForeignDefense()

if __name__ == '__main__':
    b = Forwards('巴蒂尔')
    ym = Guards('姚明')
    m = Translator('麦克格雷迪')
    b.Attack()
    m.Defense()
    ym.Attack()
    ym.Defense()
上一篇下一篇

猜你喜欢

热点阅读