跳到主要内容

23、Python - 策略模式

基本介绍

策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。

也就是说该类在不同的环境下,能够调用不同的策略算法。

特点:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换

该模式属于行为型模式。

案例图示

如一个人旅游时,当他身在不同的国家中便要说不同的语言:

 

优缺点

优点:

  • 算法可以自由切换
  • 避免使用多重条件判断
  • 扩展性良好

缺点:

  • 策略类会增多
  • 所有策略类都需要对外暴露

代码实现

用Python实现策略模式:

# 人
class People(object):
    def __init__(self):
        self.strategy = {}

    def get_strategy(self, location):
        strategy = self.strategy.get(location)
        if strategy:
            return strategy()
        else:
            raise AttributeError("不会这个位置的语言")

    def register_strategy(self, location, strategy):
        self.strategy[location] = strategy
# 策略类
class Strategy(object):

    @staticmethod
    def speak_english():
        return "说英文"

    @staticmethod
    def speak_chinese():
        return "说中文"
# 位置
class Location(object):
    def __init__(self, location):
        self.location = location
if __name__ == '__main__':
    person = People()
    location = Location("美国")

    注册地理位置的策略
    person.register_strategy(location.location, Strategy.speak_english)
    获取在美国的策略
    print(person.get_strategy("美国"))

    location = Location("中国")
    注册地理位置的策略
    person.register_strategy(location.location, Strategy.speak_chinese)
    获取在中国的策略
    print(person.get_strategy("中国"))

# 说英文
# 说中文