- 定义一系列的算法,把它们封装起来,并且使它们可相互替换;
- 在有多种算法相似的情况下,使用if...else复杂且难以维护;当一个系统有许多许多类,而区分它们的只是他们直接的行为时可以使用策略模式。
- 策略模式中,算法可以自由切换,能避免使用多重条件判断,扩展性良好;
- 同时存在问题:策略类会增多,且需要对外暴露。
class TravelStrategy(object): # 出行策略
def travelAlgorithm(self):
pass
class AirplaneStrategy(TravelStrategy):
def travelAlgorithm(self):
print("坐飞机出行....")
class TrainStrategy(TravelStrategy):
def travelAlgorithm(self):
print("坐高铁出行....")
class CarStrategy(TravelStrategy):
def travelAlgorithm(self):
print("自驾出行....")
class BicycleStrategy(TravelStrategy):
def travelAlgorithm(self):
print("骑车出行....")
class TravelInterface(object):
def __init__(self, travel_strategy):
self.travel_strategy = travel_strategy
def set_strategy(self, travel_strategy):
self.travel_strategy = travel_strategy
def travel(self):
return self.travel_strategy.travelAlgorithm()
travel = TravelInterface(AirplaneStrategy()) # 坐飞机
travel.travel()
travel.set_strategy(TrainStrategy()) # 改开车
travel.travel()
网友评论