返回轻松掌握pyt......登陆

轻松掌握python设计模式之策略模式

巴扎黑2017-01-12 14:07:22321

本文实例为大家分享了python策略模式代码,供大家参考,具体内容如下

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

"""

策略模式

"""

import types

  

class StrategyExample:

 def __init__(self, func=None):

  self.name = '策略例子0'

  if func is not None:

   """给实例绑定方法用的,不会影响到其他实例"""

   self.execute = types.MethodType(func, self)

  

 def execute(self):

  print(self.name)

  

def execute_replacement1(self):

 print(self.name + ' 从执行1')

  

  

def execute_replacement2(self):

 print(self.name + ' 从执行2')

  

  

if __name__ == '__main__':

 strat0 = StrategyExample()

  

 strat1 = StrategyExample(execute_replacement1)

 strat1.name = '策略例子1'

  

 strat2 = StrategyExample(execute_replacement2)

 strat2.name = '策略例子2'

  

 strat0.execute()

 strat1.execute()

 strat2.execute()

运行结果如图:

20161118152519646.jpg

最新手记推荐

• 用composer安装thinkphp框架的步骤• 省市区接口说明• 用thinkphp,后台新增栏目• 管理员添加编辑删除• 管理员添加编辑删除

全部回复(0)我要回复

暂无评论~
  • 取消回复发送