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

策略模式终极解决方案之策略机

我们在开发时经常会遇到一堆的if else …, 或者switch, 比如我们常见的全局异常处理等, 像类似这种很多if else 或者多场景模式下, 策略模式是非常受欢迎的一种设计模式, 然而, 一个好的策略模式却不是那么容易写出来.

我在工作中也因为写烦了switch,if else 觉得很不优雅, 因此,我考虑是否有一套统一的解决方案呢?

思考我问题的初衷, 在什么策略下, 满足什么条件执行什么动作, 返回什么值, 这就是策略模式需要解决的核心问题, 大眼一看好似有点类似状态机? 然而它并不是状态机, 状态机是比较笨重, 而策略机应该是足够轻量的.

我们再来看核心问题,关于什么策略,满足什么条件执行什么动作,返回什么值, 是一个明显的dsl语法, 因此, 我的基本语法糖已确立: strategy.of().when().perform()或者strategy.of().perform(), 因为有时我们并不需要条件, 仅仅策略即可.

我们要实现上述语法糖, 就得设计一套规则, 使其可以满足dsl, 并且是合理的, 如此, 基本定义已确定, 如下:

/*** {@link StrategyMachineBuilder}* @param <S> strategy* @param <C> context* @param <R> result*/
public interface StrategyMachineBuilder<S,C,R> {Of<S,C,R> of(S s);StrategyMachine<S,C,R> build(String id);
}
/*** {@link Of}* @param <S> strategy* @param <C> context* @param <R> result*/
public interface Of<S,C,R> {When<S,C,R> when(Condition<S,C,R> condition);StrategyMachineBuilder<S,C,R> perform(Action<C,R> action);
}
/*** {@link When}* @param <S> strategy* @param <C> context* @param <R> result*/
public interface When<S,C,R> {StrategyMachineBuilder<S,C,R> perform(Action<C,R> action);
}

/*** {@link Condition}* @param <S> strategy* @param <C> context* @param <R> result*/
public interface Condition<S,C,R> {boolean isSatisfied(S s,C c);
}
/*** {@link Action}* @param <C> context* @param <R> result*/
public interface Action<C,R> {R apply(C c);
}
/*** {@link Strategy}* @param <S> strategy* @param <C> context* @param <R> result*/
public interface Strategy<S, C, R> {S strategy();Condition<S,C,R> condition();Action<C, R> action();Strategy<S,C,R> strategy(S s);Strategy<S,C,R> condition(Condition<S,C,R> condition);Strategy<S,C,R> action(Action<C,R> action);
}
/*** {@link StrategyMachine}* @param <S> strategy* @param <C> context* @param <R> result*/
public interface StrategyMachine<S,C,R> {R apply(S s, C c);
}

如此: 架构已经构建完毕, 剩下的工作就很简单了, 实现此架构即可.

/*** {@link StrategyMachineBuilderImpl}* @param <S> strategy* @param <C> context* @param <R> result*/
class StrategyMachineBuilderImpl<S,C,R> implements StrategyMachineBuilder<S,C,R>{private final Map<S, List<Strategy<S,C,R>>> map = new ConcurrentHashMap<>();@Overridepublic Of<S, C, R> of(S s) {map.computeIfAbsent(s, k -> new ArrayList<>());Strategy<S,C,R> strategy = new StrategyImpl();map.get(s).add(strategy);return new OfImpl(strategy);}@Overridepublic StrategyMachine<S, C, R> build(String id) {StrategyMachineImpl<S, C, R> machine = new StrategyMachineImpl<>(map);StrategyCache.put(id, machine);return machine;}public class OfImpl implements Of<S,C,R>{private final Strategy<S,C,R> strategy;OfImpl(Strategy<S,C,R> strategy){this.strategy = strategy;}@Overridepublic When<S, C, R> when(Condition<S,C,R> condition) {this.strategy.condition(condition);return new WhenImpl(strategy);}@Overridepublic StrategyMachineBuilder<S, C, R> perform(Action<C, R> action) {this.strategy.action(action);return StrategyMachineBuilderImpl.this;}}public class WhenImpl implements When<S,C,R> {private final Strategy<S,C,R> strategy;WhenImpl(Strategy<S,C,R> strategy){this.strategy = strategy;}@Overridepublic StrategyMachineBuilder<S, C, R> perform(Action<C, R> action) {this.strategy.action(action);return StrategyMachineBuilderImpl.this;}}public class StrategyImpl implements Strategy<S, C, R> {private S strategy;private Condition<S,C,R> condition;private Action<C, R> action;@Overridepublic S strategy() {return this.strategy;}@Overridepublic Condition<S,C,R> condition() {return this.condition;}@Overridepublic Action<C, R> action() {return this.action;}@Overridepublic Strategy<S, C, R> strategy(S s) {this.strategy = s;return this;}@Overridepublic Strategy<S, C, R> condition(Condition<S,C,R> condition) {this.condition = condition;return this;}@Overridepublic Strategy<S, C, R> action(Action<C, R> action) {this.action = action;return this;}}
}
/*** Strategy Machine Impl* @param <S> strategy* @param <C> context* @param <R> result*/
class StrategyMachineImpl<S,C,R> implements StrategyMachine<S,C,R> {private final Map<S, List<Strategy<S,C,R>>> map;public StrategyMachineImpl(Map<S, List<Strategy<S,C,R>>> map){this.map = map;}@Overridepublic R apply(S s, C c) {List<Strategy<S, C, R>> strategies = map.get(s);if (strategies==null||strategies.isEmpty()){throw new RuntimeException("no strategy found for "+s);}for (Strategy<S, C, R> strategy : strategies) {// 如果没有condition,直接执行actionif (strategy.condition()==null) {return strategy.action().apply(c);}// 如果有condition,先判断是否满足condition,满足则执行actionif (strategy.condition().isSatisfied(s,c)){return strategy.action().apply(c);}}// 未发现策略关于s的conditionthrow new RuntimeException("no strategy found of met condition for "+s);}
}
/*** Strategy Machine Factory*/
public class StrategyMachineFactory {public static <S,C,R> StrategyMachineBuilder<S,C,R> create() {return new StrategyMachineBuilderImpl<>();}public static <S,C,R> StrategyMachine<S,C,R> get(String id) {return (StrategyMachine<S, C, R>) StrategyCache.get(id);}
}
/*** {@link StrategyCache}*/
class StrategyCache {private static final Map<String,StrategyMachine<?,?,?>> CACHE = new java.util.concurrent.ConcurrentHashMap<>();public static void put(String id, StrategyMachine<?,?,?> machine) {CACHE.put(id, machine);}public static StrategyMachine<?,?,?> get(String id) {return CACHE.get(id);}
}

如此, 策略机已实现完毕. 下面给出两种场景例子
一. 不同年龄吃不同分量的药
Example:
Under the age of 12, take 20 milligrams of medication per day;
12-18 years old, taking 30 milligrams a day
18-30 years old, taking 40 milligrams a day
30-50 years old, taking 45 milligrams a day
Eating 42 milligrams for those over 50 years old

class MedicineStrategy {private static StrategyMachine<String, MedicineContext, Void> strategy;static {StrategyMachineBuilder<String, MedicineContext, Void> machineBuilder = StrategyMachineFactory.create();strategy = machineBuilder.of("").when((s, c) -> c.age < 12).perform((c) -> {System.out.println("Under the age of 12, take 20 milligrams of medication per day;");return Void.TYPE.cast(null);}).of("").when((s, c) -> c.age >= 12 && c.age < 18).perform((c) -> {System.out.println("12-18 years old, taking 30 milligrams a day");return Void.TYPE.cast(null);}).of("").when((s, c) -> c.age >= 18 && c.age < 30).perform((c) -> {System.out.println("18-30 years old, taking 40 milligrams a day");return Void.TYPE.cast(null);}).of("").when((s, c) -> c.age >= 30 && c.age < 50).perform((c) -> {System.out.println("30-50 years old, taking 45 milligrams a day");return Void.TYPE.cast(null);}).of("").when((s, c) -> c.age >= 50).perform((c) -> {System.out.println("Eating 42 milligrams for those over 50 years old");return Void.TYPE.cast(null);}).build("medicine");}public static StrategyMachine<String, MedicineContext, Void> get() {// StrategyMachine<String, MedicineContext, Void> strategy = StrategyMachineFactory.get("medicine");return strategy;}@Data@AllArgsConstructor@NoArgsConstructorpublic static class MedicineContext {private int age;}public static void main(String[] args) {get().apply("", new MedicineContext(10));}}

二. 计算机

		StrategyMachineBuilder<String, StrategyContext, Number> machineBuilder = StrategyMachineFactory.create();machineBuilder.of("加法").perform(strategyContext -> strategyContext.a + strategyContext.b);machineBuilder.of("减法").perform(strategyContext -> strategyContext.a - strategyContext.b);machineBuilder.of("乘法").perform(strategyContext -> strategyContext.a * strategyContext.b);// 除法,当c==1时,忽略小数位, 当c==2时不忽略machineBuilder.of("除法").when((s, strategyContext) -> strategyContext.c == 1).perform(strategyContext -> strategyContext.a / strategyContext.b);machineBuilder.of("除法").when((s, strategyContext) -> strategyContext.c == 2).perform(strategyContext -> (strategyContext.a * 1.0d) / (strategyContext.b * 1.0d));StrategyMachine<String, StrategyContext, Number> strategyMachine = machineBuilder.build("test");// StrategyMachine<String, StrategyContext, Number> strategyMachine =  StrategyMachineFactory.get("test");System.out.println(strategyMachine.apply("加法", new StrategyContext(1, 2, 1)));System.out.println(strategyMachine.apply("减法", new StrategyContext(1, 2, 1)));System.out.println(strategyMachine.apply("乘法", new StrategyContext(1, 2, 1)));System.out.println(strategyMachine.apply("除法", new StrategyContext(1, 2, 1)));System.out.println(strategyMachine.apply("除法", new StrategyContext(1, 2, 2)));

源码地址: https://github.com/zhangpan-soft/dv-commons

相关文章:

策略模式终极解决方案之策略机

我们在开发时经常会遇到一堆的if else …, 或者switch, 比如我们常见的全局异常处理等, 像类似这种很多if else 或者多场景模式下, 策略模式是非常受欢迎的一种设计模式, 然而, 一个好的策略模式却不是那么容易写出来. 我在工作中也因为写烦了switch,if else 觉得很不优雅, 因…...

linux 常用指令目录大纲

Linux下的Signal信号处理及详解&#xff0c;test ok-CSDN博客 Linux下怎样判断一个binary是否可以debug//test ok_感知算法工程师的博客-CSDN博客 linux file命令的用法//test ok-CSDN博客 linux下生成core dump方法与gdb解析core dump文件//test ok-CSDN博客 linux readel…...

webpack该如何打包

1.我们先创建一个空的大文件夹 2.打开该文件夹的终端 输入npm init -y 2.1.打开该文件夹的终端 2.2在该终端运行 npm init -y 3.安装webpack 3.1打开webpack网址 点击“中文文档” 3.2点击“指南”在点击“起步” 3.3复制基本安装图片画线的代码 4.在一开始的文件夹下在创建一…...

【STM32】TIM定时器输入捕获

1 输入捕获 1.1 输入捕获简介 IC&#xff08;Input Capture&#xff09;输入捕获 输入捕获模式下&#xff0c;当通道输入引脚出现指定电平跳变时&#xff08;上升沿/下降沿&#xff09;&#xff0c;当前CNT的值将被锁存到CCR中&#xff08;把CNT的值读出来&#xff0c;写入到…...

webrtc 设置不获取鼠标 启用回声消除

数 getDisplayMedia()(属于 navigator.mediaDevices 的一部分)与 getUserMedia() 类似,用于打开显示内容(或部分内容,如窗口)。返回的 MediaStream 与使用 getUserMedia() 时相同。 显示鼠标与否 getDisplayMedia() 的约束条件与常规视频或音频输入资源的限制不同。 {…...

JVM虚拟机:如何查看JVM初始和最终的参数?

本文重点 在前面的课程中&#xff0c;我们学习了如何查看当前程序所处于的xx参数&#xff0c;本文再介绍一种如何参看JVM的xx参数&#xff1f; 查看JVM的所有初始化参数 方式一&#xff1a;java -XX:PrintFlagsInitial 方式二&#xff1a;java -XX:PrintFlagsInitial -versio…...

JVM Optimization Learning(五)

目录 一、JVM Optimization 1、G1 1、G1内存模型 2、基础概念 3、G1特点&#xff1a; 4、CMS日志分析 5、G1日志分析 2、GC参数 2.1、GC常用参数 2.2、Parallel常用参数 2.3、CMS常用参数 2.4、G1常用参数 一、JVM Optimization 1、G1 G1官网说明&#xff1a;Gar…...

Java项目学生管理系统一前后端环境搭建

在现代的软件开发中&#xff0c;学生管理系统是一个常见的应用场景。通过学生管理系统&#xff0c;学校能够方便地管理学生的信息、课程安排和成绩等数据。本文将介绍如何使用Java语言搭建一个学生管理系统的前后端环境&#xff0c;并提供一个简单的示例。 1.环境搭建 学生管…...

LeetCode:169.多数元素(哈希表)

题目 第一版 思路 直接开个哈希表&#xff0c;存储每个数组中的数字和对应出现的次数。然后排序后找出对应最大value值的key。 代码 class Solution {public int majorityElement(int[] nums) {Map<Integer,Integer>map new HashMap<Integer,Integer>();for(…...

Linux指令学习

目录 1.ls指令 2.pwd命令 3.cd 指令 4. touch指令 5.mkdir指令 6.rmdir指令 && rm 指令 7.man指令 8.cp指令 9.mv指令 10.cat指令 11.more指令 12.less指令 13.head指令 14.find指令&#xff1a; -name 15.grep指令 16.zip/unzip指令&#xff1a; 17.tar…...

vue2+datav可视化数据大屏(1)

开始 &#x1f4d3; 最近打算出一个前端可视化数据大屏的系列专栏&#xff0c;这次将很全面的教大家设计可视化大屏&#xff0c;从开始到打包结束&#xff0c;其中&#xff0c;包括如何设计框架&#xff0c;如何封装axios&#xff0c;等等&#xff0c;本次使用的数据均为mock数…...

Linux 多进程并发设计-进程对核的亲缘设置

1设计结构 2 设计优点 1 充分利用多核系统的并发处理能力2 负载均衡3 职责明确&#xff0c;管理进程仅负责管理&#xff0c;工作进程仅负责处理业务逻辑 3 演示代码: //main.cpp #define _GNU_SOURCE #include<sys/types.h> #include<sys/wait.h> #include <…...

Javascript 函数介绍

Javascript 函数介绍 很多教程书一上来就讲解一堆语法&#xff0c;例如函数定义、函数调用什么。等读者看完了函数这一章都没搞懂什么是函数。 在讲解什么叫函数之前&#xff0c;我们先看下面一段代码&#xff1a; <!DOCTYPE html> <html xmlns"http://www.w3.…...

php 粉丝关注功能实现

实现粉丝关注功能的步骤如下&#xff1a; 创建用户表&#xff08;user&#xff09;和关注表&#xff08;follow&#xff09;&#xff1a; CREATE TABLE user (id int(11) NOT NULL AUTO_INCREMENT,username varchar(255) NOT NULL,email varchar(255) NOT NULL,password varc…...

深入浅出理解kafka ---- 万字总结

1.Kafka简介 Kafka 本质上是一个 MQ&#xff08;Message Queue&#xff09;&#xff0c;使用消息队列的优点&#xff1a; 解耦&#xff1a;允许独立的扩展或修改队列两边的处理过程。可恢复性&#xff1a;即使一个处理消息的进程挂掉&#xff0c;加入队列中的消息仍然可以在系…...

一对一聊天

服务端 package 一对一用户;import java.awt.BorderLayout; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.ServerSocket; import java.net.Socket; import java.util.Vector;…...

IDEA版SSM入门到实战(Maven+MyBatis+Spring+SpringMVC) -Mybatis查询中返回值四种情况

第一章 Mybatis查询中返回值四种情况 1.1 查询单行数据返回单个对象 /*** 通过id获取员工信息*/ public Employee selectEmpById(int empId);<select id"selectEmpById" resultType"employee">SELECTid,last_name,email,salaryFROMtbl_employeeWHE…...

华为云安全组规则

初始发布cce,快被安全组搞死了。现在把自己的研究成果综合一下,在这里给自己留痕,希望对迷惑的朋友有帮助。 先搞懂安全组是个啥东东: 安全组规则 操作场景 安全组实际是网络流量访问策略,通过访问策略可以控制流量入方向规则和出方向规则,通过这些规则可以为加入安全组…...

MySQL之binlog文件过多处理方法

背景 MySQL由于大量读写&#xff0c;导致binlog文件特别的多。从而导致服务器disk空间不足问题。 先备份binlog文件 tar -zcvf mysql.tar.gz mysql/data/mysql-bin.00* 修改MySQL配置 binlog过期时间 show variables like expire_logs_days; 这里 0 表示 永不过期 如果为 n…...

力扣面试150题 | 88.合并两个有序数组

力扣面试150题 &#xff5c; 88.合并两个有序数组 题目描述解题思路代码实现复杂度分析 题目描述 88.合并两个有序数组 给你两个按 非递减顺序 排列的整数数组 nums1 和 nums2&#xff0c;另有两个整数 m 和 n &#xff0c;分别表示 nums1 和 nums2 中的元素数目。 请你 合并…...

Cursor实现用excel数据填充word模版的方法

cursor主页&#xff1a;https://www.cursor.com/ 任务目标&#xff1a;把excel格式的数据里的单元格&#xff0c;按照某一个固定模版填充到word中 文章目录 注意事项逐步生成程序1. 确定格式2. 调试程序 注意事项 直接给一个excel文件和最终呈现的word文件的示例&#xff0c;…...

【杂谈】-递归进化:人工智能的自我改进与监管挑战

递归进化&#xff1a;人工智能的自我改进与监管挑战 文章目录 递归进化&#xff1a;人工智能的自我改进与监管挑战1、自我改进型人工智能的崛起2、人工智能如何挑战人类监管&#xff1f;3、确保人工智能受控的策略4、人类在人工智能发展中的角色5、平衡自主性与控制力6、总结与…...

TDengine 快速体验(Docker 镜像方式)

简介 TDengine 可以通过安装包、Docker 镜像 及云服务快速体验 TDengine 的功能&#xff0c;本节首先介绍如何通过 Docker 快速体验 TDengine&#xff0c;然后介绍如何在 Docker 环境下体验 TDengine 的写入和查询功能。如果你不熟悉 Docker&#xff0c;请使用 安装包的方式快…...

C++ 求圆面积的程序(Program to find area of a circle)

给定半径r&#xff0c;求圆的面积。圆的面积应精确到小数点后5位。 例子&#xff1a; 输入&#xff1a;r 5 输出&#xff1a;78.53982 解释&#xff1a;由于面积 PI * r * r 3.14159265358979323846 * 5 * 5 78.53982&#xff0c;因为我们只保留小数点后 5 位数字。 输…...

【JavaSE】绘图与事件入门学习笔记

-Java绘图坐标体系 坐标体系-介绍 坐标原点位于左上角&#xff0c;以像素为单位。 在Java坐标系中,第一个是x坐标,表示当前位置为水平方向&#xff0c;距离坐标原点x个像素;第二个是y坐标&#xff0c;表示当前位置为垂直方向&#xff0c;距离坐标原点y个像素。 坐标体系-像素 …...

智能仓储的未来:自动化、AI与数据分析如何重塑物流中心

当仓库学会“思考”&#xff0c;物流的终极形态正在诞生 想象这样的场景&#xff1a; 凌晨3点&#xff0c;某物流中心灯火通明却空无一人。AGV机器人集群根据实时订单动态规划路径&#xff1b;AI视觉系统在0.1秒内扫描包裹信息&#xff1b;数字孪生平台正模拟次日峰值流量压力…...

【7色560页】职场可视化逻辑图高级数据分析PPT模版

7种色调职场工作汇报PPT&#xff0c;橙蓝、黑红、红蓝、蓝橙灰、浅蓝、浅绿、深蓝七种色调模版 【7色560页】职场可视化逻辑图高级数据分析PPT模版&#xff1a;职场可视化逻辑图分析PPT模版https://pan.quark.cn/s/78aeabbd92d1...

人机融合智能 | “人智交互”跨学科新领域

本文系统地提出基于“以人为中心AI(HCAI)”理念的人-人工智能交互(人智交互)这一跨学科新领域及框架,定义人智交互领域的理念、基本理论和关键问题、方法、开发流程和参与团队等,阐述提出人智交互新领域的意义。然后,提出人智交互研究的三种新范式取向以及它们的意义。最后,总结…...

宇树科技,改名了!

提到国内具身智能和机器人领域的代表企业&#xff0c;那宇树科技&#xff08;Unitree&#xff09;必须名列其榜。 最近&#xff0c;宇树科技的一项新变动消息在业界引发了不少关注和讨论&#xff0c;即&#xff1a; 宇树向其合作伙伴发布了一封公司名称变更函称&#xff0c;因…...

【Veristand】Veristand环境安装教程-Linux RT / Windows

首先声明&#xff0c;此教程是针对Simulink编译模型并导入Veristand中编写的&#xff0c;同时需要注意的是老用户编译可能用的是Veristand Model Framework&#xff0c;那个是历史版本&#xff0c;且NI不会再维护&#xff0c;新版本编译支持为VeriStand Model Generation Suppo…...