简单的策略模式
Tofloor
poster avatar
z85525006
deepin
2012-06-13 21:18
Author
策略模式是对算法的一种封装。
  1. class Opertion(object):
  2.     def oper(a, b):
  3.         pass
  4. class Sub(object):
  5.     def oper(self,a, b):
  6.         return a - b
  7.    
  8. class Div(object):
  9.     def oper(self,a, b):
  10.         return float(a) / b
  11.    
  12. class Add(object):
  13.     def oper(self,a, b):
  14.         return a + b
  15. class Cls(object):
  16.     def __init__(self, oper):
  17.         self.op = oper
  18.         
  19.     def oper(self, a, b):   
  20.         return self.op.oper(a, b)
  21.         
  22. if __name__ == "__main__":
  23.     cls = Cls(Add())
  24.     print cls.oper(3, 4)
  25.     cls = Cls(Sub())
  26.     print cls.oper(3, 4)
  27.     cls = Cls(Div())
  28.     print cls.oper(3, 4)
Copy the Code
Reply Favorite View the author
All Replies
cnchanghai
deepin
2012-06-14 04:40
#1
这个有啥用
Reply View the author