找回密码
 立即注册
首页 业界区 业界 [设计模式]行为型-策略模式

[设计模式]行为型-策略模式

班闵雨 2025-6-9 08:36:52
前言

策略模式定义了一系列算法,并将每个算法封装起来,使它们可以互相替换,且算法的变换不会影响使用算法的客户。
在项目开发中,我们经常要根据不同的场景,采取不同的措施,也就是不同的策略。假设我们需要对a、b这两个整数进行计算,根据条件的不同,需要执行不同的计算方式。我们可以把所有的操作都封装在同一个函数中,然后根据if ... else ...的形式来调用不同的计算方式,这种方式称为硬编码。
在实际应用中,随着功能和体验的不断增长,我们需要经常添加/修改策略,进而需要不断修改已有代码,这不仅会让这个函数越来越难以维护,还会因为修改带来一些Bug。因此,为了解耦,我们需要使用策略模式,定义一些独立的类来封装不同的算法,每一个类封装一个具体的算法。
示例代码

策略模式的重点在于策略的设定,以及普通类Operator和策略CalStrategy的对接。通过更换实现同一接口的不同策略类。降低了Operator的维护成本,解耦算法实现。
Go

strategy.go
  1. package strategy  
  2.   
  3. // CalStrategy 是一个策略类  
  4. type CalStrategy interface {  
  5.     do(int, int) int  
  6. }  
  7.   
  8. // Add 为加法策略  
  9. type Add struct{}  
  10.   
  11. func (*Add) do(a, b int) int {  
  12.     return a + b  
  13. }  
  14.   
  15. // Reduce 为减法策略  
  16. type Reduce struct{}  
  17.   
  18. func (*Reduce) do(a, b int) int {  
  19.     return a - b  
  20. }  
  21.   
  22. // Operator 是具体的策略执行者  
  23. type Operator struct {  
  24.     strategy CalStrategy  
  25. }  
  26.   
  27. // 设置策略  
  28. func (o *Operator) setStrategy(strategy CalStrategy) {  
  29.     o.strategy = strategy  
  30. }  
  31.   
  32. // 调用策略中的方法  
  33. func (o *Operator) calc(a, b int) int {  
  34.     return o.strategy.do(a, b)  
  35. }
复制代码
单元测试
  1. package strategy  
  2.   
  3. import "testing"  
  4.   
  5. func TestStrategy(t *testing.T) {  
  6.     operator := Operator{}  
  7.     operator.setStrategy(&Add{})  
  8.     if operator.calc(1, 2) != 3 {  
  9.        t.Fatal("Add strategy error")  
  10.     }  
  11.   
  12.     operator.setStrategy(&Reduce{})  
  13.     if operator.calc(2, 1) != 1 {  
  14.        t.Fatal("Reduce strategy error")  
  15.     }  
  16. }
复制代码
Python
  1. from abc import ABC, abstractmethod
  2. class CalStrategy(ABC):
  3.     """策略类
  4.     """
  5.     @abstractmethod
  6.     def do(self, a: int, b: int) -> int:
  7.         pass
  8. class Add(CalStrategy):
  9.     """加法策略
  10.     """
  11.     def do(self, a: int, b: int) -> int:
  12.         return a + b
  13. class Reduce(CalStrategy):
  14.     """减法策略
  15.     """
  16.     def do(self, a: int, b: int) -> int:
  17.         return a - b
  18. class Operator:
  19.     """策略执行者
  20.     """
  21.     def __init__(self):
  22.         self.strategy = None
  23.     def set_strategy(self, strategy: CalStrategy):
  24.         """设置策略
  25.         """
  26.         self.strategy = strategy
  27.     def calc(self, a: int, b: int) -> int:
  28.         """调用策略中的方法
  29.         """
  30.         return self.strategy.do(a, b)
  31. if __name__ == "__main__":
  32.     operator = Operator()
  33.     operator.set_strategy(Add())
  34.     print(operator.calc(1, 2))
  35.     operator.set_strategy(Reduce())
  36.     print(operator.calc(4, 3))
复制代码
参考


  • 孔令飞 - 企业级Go项目开发实战

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!
您需要登录后才可以回帖 登录 | 立即注册