美文网首页
Python中的策略模式

Python中的策略模式

作者: Raymond_行者 | 来源:发表于2017-10-10 16:41 被阅读0次

    策略模式学习与记录

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

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

    代码实现如下

    
    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中的策略模式

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