​设计模式:策略模式解析与Go语言实现

60 阅读2分钟

1. 引言

策略模式(Strategy Pattern)是软件设计中的一种行为型模式,它定义了算法族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化独立于使用算法的客户。

DALL·E 2023-11-19 16.52.39 - A conceptual illustration for the Strategy design pattern in software engineering. The image should depict a central figure or system surrounded by va.png

2. 策略模式的结构

策略模式涉及三个主要角色:

  • 上下文(Context) :用一个具体策略对象来配置,维护一个对策略对象的引用。

  • 策略接口(Strategy) :定义了一个公共接口,各种不同的算法以不同的方式实现这个接口。

  • 具体策略(Concrete Strategy) :实现策略接口的具体算法。

3. Go语言实现示例

以下是使用Go语言实现策略模式的示例:

package main​import "fmt"​// 策略接口type Strategy interface {  Execute(a, b int) int}​// 具体策略Atype ConcreteStrategyA struct{}​func (s *ConcreteStrategyA) Execute(a, b int) int {  return a + b}​// 具体策略Btype ConcreteStrategyB struct{}​func (s *ConcreteStrategyB) Execute(a, b int) int {  return a - b}​// 上下文type Context struct {  strategy Strategy}​func NewContext(strategy Strategy) *Context {  return &Context{    strategy: strategy,  }}​func (c *Context) SetStrategy(strategy Strategy) {  c.strategy = strategy}​func (c *Context) ExecuteStrategy(a, b int) int {  return c.strategy.Execute(a, b)}​func main() {  context := NewContext(new(ConcreteStrategyA))  fmt.Println("10 + 5 =", context.ExecuteStrategy(10, 5))​  context.SetStrategy(new(ConcreteStrategyB))  fmt.Println("10 - 5 =", context.ExecuteStrategy(10, 5))}

4. 策略模式的应用场景

策略模式适用于以下场景:

  • 许多相关的类仅仅是行为有异。

  • 需要使用一个算法的不同变体。

  • 算法使用客户不应该知道的数据。

5. 策略模式的优缺点

优点:

  • 定义了一系列可重用的算法和行为。
  • 算法可以自由切换。
  • 易于扩展。

缺点:

  • 客户必须了解不同的策略。

  • 增加了对象的数量。

6. 结语

策略模式提供了一种将算法封装在独立的策略类中的方法,并在运行时决定使用哪个算法的方式,从而使得算法可以独立于使用它的客户端变化。