Python中的策略模式

策略模式学习与记录

  • 设计原则
    • 找出应用中可能需要改变之处, 把他们独立出来, 不要和那些不需要改变的代码混在一起
    • 针对接口编程而不是针对实现编程

不要被类的实现拖垮你的代码, 针对接口编程的关键, 在于利用多态 执行时会根据状况执行到真正的行为

代码实现如下


import abc


class FlyBehavior:
    """ pass """
    __metaclass__ = abc.ABCMeta

    @classmethod
    @abc.abstractmethod
    def fly(cls):
        """ pass """


class FlyWithWings(FlyBehavior):
    """ pass """
    @classmethod
    def fly(cls):
        """ pass """
        print('I can fly')


class FlyNoWay(FlyBehavior):
    """ pass """
    @classmethod
    def fly(cls):
        """ pass """


class QuackBehavior:
    """ pass """
    __metaclass__ = abc.ABCMeta

    @classmethod
    @abc.abstractmethod
    def quack(cls):
        """ pass """


class Quack(QuackBehavior):
    """ pass """
    @classmethod
    def quack(cls):
        """ pass """
        print('I can quack ... gua gua gua !')


class Squeak(QuackBehavior):
    """ pass """
    @classmethod
    def quack(cls):
        """ pass """
        print('I can quack ... zhi zhi zhi !')


class QuackNotWay(QuackBehavior):
    """ pass """
    @classmethod
    def quack(cls):
        """ pass """


class Duck:
    """ pass """
    def __init__(self, _fly, _quack):
        """ pass """
        self.__quack = _quack()
        self.__fly = _fly()

    def swim(self):
        """ pass """
        print('swiming ...!')

    def display(self):
        """ pass """
        self.__quack.quack()
        self.__fly.fly()
        self.swim()


class MallardDuck(Duck):
    """ pass """
    def __init__(self, _fly, _quack):
        """ pass """
        print('MallardDuck')
        super(MallardDuck, self).__init__(_fly, _quack)


class RubberDuck(Duck):
    """ 橡皮鸭 """
    def __init__(self, _fly, _quack):
        """ pass """
        print('RubberDuck')
        super(RubberDuck, self).__init__(_fly, _quack)


class DecoyDuck(Duck):
    """ 诱饵鸭 """
    def __init__(self, _fly, _quack):
        """ pass """
        print('DecoyDuck')
        super(DecoyDuck, self).__init__(_fly, _quack)

if __name__ == '__main__':
    mallar = MallardDuck(FlyWithWings, Quack)
    mallar.display()
    rubber = RubberDuck(FlyNoWay, Squeak)
    rubber.display()
    decoy = DecoyDuck(FlyNoWay, QuackNotWay)
    decoy.display()

你可能感兴趣的:(Python中的策略模式)