当前位置: 首页 > news >正文

GPT带我学-设计模式13-策略模式

概述

策略模式

例子

你可以创建一个策略工厂(Strategy Factory)来根据传入的 orgId 动态地选择合适的策略。以下是实现示例:

  1. 首先,定义策略接口和具体策略类:
public interface CardPathStrategy {String generatePath();
}public class OrganizationAStrategy implements CardPathStrategy {@Overridepublic String generatePath() {return "path/for/organizationA";}
}public class OrganizationBStrategy implements CardPathStrategy {@Overridepublic String generatePath() {return "path/for/organizationB";}
}
  1. 创建一个策略工厂 CardPathStrategyFactory 来根据 orgId 返回相应的策略:
import java.util.HashMap;
import java.util.Map;public class CardPathStrategyFactory {private static final Map<String, CardPathStrategy> strategies = new HashMap<>();static {strategies.put("orgA", new OrganizationAStrategy());strategies.put("orgB", new OrganizationBStrategy());// 添加更多策略}public static CardPathStrategy getStrategy(String orgId) {return strategies.get(orgId);}
}
  1. 在你的业务逻辑中使用策略工厂:
public class CardPathGenerator {public static void main(String[] args) {String orgId = "orgA";  // 这个可以是传入的参数CardPathStrategy strategy = CardPathStrategyFactory.getStrategy(orgId);if (strategy == null) {throw new IllegalArgumentException("No strategy found for orgId: " + orgId);}CardPathContext context = new CardPathContext(strategy);System.out.println(context.generateCardPath());  // 输出:path/for/organizationAorgId = "orgB";  // 更改组织IDstrategy = CardPathStrategyFactory.getStrategy(orgId);if (strategy == null) {throw new IllegalArgumentException("No strategy found for orgId: " + orgId);}context.setStrategy(strategy);System.out.println(context.generateCardPath());  // 输出:path/for/organizationB}
}

通过这种方式,你可以根据传入的 orgId 动态地选择不同的策略。工厂类 CardPathStrategyFactory 负责管理策略的创建和选择逻辑,这使得代码更简洁且易于维护。

http://www.lryc.cn/news/399862.html

相关文章:

  • 【Linux】Ubuntu配置JDK环境、MySQL环境
  • 【ElasticSearch】ES 5.6.15 向量插件支持
  • Kafka 高并发设计之数据压缩与批量消息处理
  • 设计模式使用场景实现示例及优缺点(行为型模式——模板方法模式)
  • ETL数据集成丨主流ETL工具(ETLCloud、DataX、Kettle)数据传输性能大PK
  • eNSP:防火墙设置模拟公司配置(二)
  • vue3 两个组件之间传值
  • 基于matlab的深度学习案例及基础知识专栏前言
  • 机器学习——L1 L2 范数 —>L1 L2正则化
  • 大模型时代,还需要跨端framework吗?
  • ASP.NET Core----基础学习05----将数据传递给视图文件的五种情况
  • Flutter实现局部刷新的几种方式
  • 力扣题解(回文子串)
  • 对数的基本概念
  • C双指针滑动窗口算法
  • WPF学习(6) -- WPF命令和通知
  • 升级到LVGL9的一些变化(后续发现再补充)
  • 当在多线程环境中使用 C++进行编程时,怎样确保线程安全以及如何处理线程之间的同步和通信?
  • 博物馆地图导航系统:高精度地图引擎与AR/VR融合,实现博物馆数字化转型
  • liunx作业笔记1
  • 大话C语言:第31篇 指针和数组的关系
  • Mysql-索引应用
  • Facebook 开源计算机视觉 (CV) 和 增强现实 (AR) 框架 Ocean
  • 【接口自动化_13课_接口自动化总结】
  • 安防管理平台LntonCVS视频汇聚融合云平台智慧火电厂安全生产管理应用方案
  • 【Web性能优化】在Vue项目中使用defer优化白屏,秒加载!
  • springboot上传图片
  • python入门:python及PyCharm安装
  • 链接追踪系列-04.linux服务器docker安装elk
  • 深入探讨微服务架构设计模式与常见实践