Design 策略模式

基本介绍

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

在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的context对象。

策略对象改变context对象的执行算法

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

案例图示

在不同的环境下,能够调用不同的策略算法:

image-20210414153854397

优缺点

优点:

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

缺点:

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

Python实现

用Python实现策略模式,一个人旅游,在不同的国家说不通的语言:

#! /usr/local/bin/python3
# -*- coding:utf-8 -*-

# 人
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("中国"))

结果如下:

说英文
说中文

Golang实现

用Golang实现策略模式,一个人旅游,在不同的国家说不通的语言:

...
posted @ 2021-04-14 15:27  云崖君  阅读(97)  评论(0编辑  收藏  举报