zoukankan      html  css  js  c++  java
  • Python策略模式实现源码分享

    1.让一个对象的某个方法可以随时改变,而不用更改对象的代码

    2.对于动态类型的Python语言,不需要定义接口

    3.基本的实现方法:用类作为参数传递

    例如:

    12_eg3.py

    class Moveable:

        def move(self):

            print('Move...')

    class MoveOnFeet(Moveable):

        def move(self):

            print("Move on Feet.")

    class MoveOnWheel(Moveable):

        def move(self):

            print("Move on Wheels.")

    class MoveObj:

        def set_move(self,moveable):

            self.moveable = moveable()

        def move(self):

            self.moveable.move()

    class Test:

        def move(slef):

            print("I'm Fly.")

    if __name__ == '__main__':

        m = MoveObj()

        m.set_move(Moveable)

        m.move()

        m.set_move(MoveOnFeet)

        m.move()

        m.set_move(MoveOnWheel)

        m.move()

        m.set_move(Test)

        m.move()

    程序的运行结果为:

    4.最简的实现方法:函数作为参数来传递

    例如:

    def movea():

        print('Move a.')

    def moveb():

        print('Move b.')

    class MoveObj:

        def set_move(self,moveable):

            self.moveable = moveable

        def move(self):

            self.moveable()

    if __name__ == '__main__':

        m = MoveObj()

        m.set_move(movea)

        m.move()

        m.set_move(moveb)

        m.move()

    程序的运行结果为:

    原文链接:http://www.maiziedu.com/wiki/python/strategy/

  • 相关阅读:
    分治法解决寻找数组中最大最小值的问题
    bootstrap动画进度条
    关于bootstrap中css样式与自己设置的css样式相撞问题
    css引入外部字体
    清除浮动
    四叶玫瑰数
    水仙花数
    nginx 配置文件服务器
    springboot 自定义拦截器 防止恶意请求
    springboot 自定义异常
  • 原文地址:https://www.cnblogs.com/space007/p/5953907.html
Copyright © 2011-2022 走看看