【设计模式】策略模式

策略模式是行为设计模式 ,核心思想是定义算法族,分别封装,并且他们可以互相替换。

该模式使得算法独立于客户端变化,解决了场景中多种算法策略交叉混杂的问题。

使用场景

  • 数据导出,需要导出为不同格式的数据(Excel、PDF、CSV等)
  • 数据计算,需要执行不同的计算公式(加减、乘除等)
  • 对接不同的数据库(mysql、pgsql等)

核心组件

  • 策略接口 :strategy interface

    • 定义算法的抽象协议

      public interface Strategy{
      void execute(Object obj);
      }

  • 策略实现类

    • 具体算法的实现类,每一个策略实现一种独立算法

      public class StringStrategy implements Strategy {
      @Override
      public void execute(Object obj) {
      System.out.println("String:" + obj);
      }
      }

      public class IntegerStrategy implements Strategy {
      @Override
      public void execute(Object obj) {
      System.out.println("Integer:" + obj);
      }
      }

  • 上下文类 :Context

    • 执行相关策略,将客户端和策略进行解耦

      public class StrategyContext {
      private Strategy strategy;

      复制代码
      public void setStrategy(Strategy strategy) {
          this.strategy = strategy;
      }
      
      public void execute(Object obj) {
          strategy.execute(obj);
      }

      }

类图

  • Application:调用类

  • StrategyContext:上下文类

  • Strategy:抽象类

  • StringStrategy:实现类

    public interface Strategy {

    复制代码
      void execute(Object obj);  

    }

    public class StringStrategy implements Strategy {
    @Override
    public void execute(Object obj) {
    System.out.println("String:" + obj);
    }
    }

    public class StrategyContext {

    复制代码
      private Strategy strategy;  
    
      public void setStrategy(Strategy strategy) {  
          this.strategy = strategy;  
      }  
    
      public void execute(Object obj) {  
          strategy.execute(obj);  
      }  

    }

    public class Application {

    复制代码
      public static void main(String[] args) {  
          StrategyContext strategyContext = new StrategyContext();  
    
    
          strategyContext.setStrategy(new StringStrategy());  
          strategyContext.execute("StringStrategy");  
    
          strategyContext.setStrategy(new IntegerStrategy());  
          strategyContext.execute(66);  
      }  

    }

模式的优缺点

优点

  • 消除了大量的判定(if-else,switch-case),提高了代码可读性
  • 符合单一原则
  • 支持动态切换算法

缺点

  • 策略类可能无限增长
  • 客户端需要了解不同策略的区别

总结

策略模式将算法从业务逻辑中解耦出来,是消除条件表达式的重要模式,能够很好的提高可读性。建议与工厂模式进行组合使用。

相关推荐
静水流深_沧海一粟7 小时前
04 | 别再写几十个参数的构造函数了——建造者模式
设计模式
StarkCoder7 小时前
从UIKit到SwiftUI的迁移感悟:数据驱动的革命
设计模式
阿星AI工作室15 小时前
给openclaw龙虾造了间像素办公室!实时看它写代码、摸鱼、修bug、写日报,太可爱了吧!
前端·人工智能·设计模式
_哆啦A梦1 天前
Vibe Coding 全栈专业名词清单|设计模式·基础篇(创建型+结构型核心名词)
前端·设计模式·vibecoding
阿闽ooo5 天前
中介者模式打造多人聊天室系统
c++·设计模式·中介者模式
小米4965 天前
js设计模式 --- 工厂模式
设计模式
头发还在的女程序员5 天前
【免费下载】企业能源管理系统
小程序·策略模式·能源管理
前端 贾公子5 天前
React 和 Vue 都离不开的表单验证库 async-validator 之策略模式的应用 (上)
vue.js·react.js·策略模式
逆境不可逃5 天前
【从零入门23种设计模式08】结构型之组合模式(含电商业务场景)
线性代数·算法·设计模式·职场和发展·矩阵·组合模式
驴儿响叮当20105 天前
设计模式之状态模式
设计模式·状态模式