"""
策略模式:在不同的时间使用不同的规则就可以考虑策略模式
定义了不同的算法,他们之间可以相互替换。此模式让算法的变化不会影响到算法的使用
实现相同的功能,有相同的调用方式,实现方式不同
此代码是策略模式和简单工厂模式的结合
"""
class ParentStrategy(object):
def __init__(self, a, b):
self.a = a
self.b = b
pass
def do_something(self):
pass
class StrategyAdd(ParentStrategy):
def __init__(self, a, b):
super(StrategyAdd, self).__init__(a, b)
pass
def do_something(self):
print(self.a + self.b)
class StrategyJian(ParentStrategy):
def __init__(self, a, b):
super(StrategyJian, self).__init__(a, b)
def do_something(self):
print(self.a - self.b)
class StrategyContext(object):
def __init__(self):
self.strategy_class = None
def create_strategy(self, strategy, a, b):
if strategy == "+":
self.strategy_class = StrategyAdd(a, b)
elif strategy == "-":
self.strategy_class = StrategyJian(a, b)
def do_things(self):
if self.strategy_class:
self.strategy_class.do_something()
if __name__ == '__main__':
context = StrategyContext()
context.create_strategy("+", 5, 6)
context.do_things()
context.create_strategy("-", 5, 6)
context.do_things()
策略模式(python)
最新推荐文章于 2024-05-20 17:12:12 发布