策略模式实战

1、代码

java 复制代码
package com.ylt.module.operation.strategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class TableUpdateContext {
    private final Map<String, TableUpdateStrategy> strategyMap;

    @Autowired
    public TableUpdateContext(List<TableUpdateStrategy> strategies) {
        // 将策略列表转换为Map,key为支持的表格类型
        this.strategyMap = strategies.stream()
                .collect(Collectors.toMap(
                        TableUpdateStrategy::getSupportedType,
                        Function.identity()
                ));
    }

    /**
     * 执行表状态更新
     */
    public void executeUpdate(String tableType, Long id, String newStatus) {
        TableUpdateStrategy strategy = strategyMap.get(tableType.toLowerCase());
        if (strategy == null) {
            throw new IllegalArgumentException("不支持的表格类型: " + tableType);
        }
        strategy.updateStatus(id, newStatus);
    }

    /**
     * 获取文件路径
     */
    public Map<String, Object> getFilePath(String tableType, Long id) {
        TableUpdateStrategy strategy = strategyMap.get(tableType.toLowerCase());
        if (strategy == null) {
            throw new IllegalArgumentException("不支持的表格类型: " + tableType);
        }
        return strategy.getFilePath(id);
    }
}

2、策略

3、实战

java 复制代码
@Transactional(propagation = Propagation.REQUIRES_NEW)
    public void approveSingle(Long id, Integer status, String reviewMsg) {
        // 单个审批逻辑
        ReviewLogDO reviewLogDO = validateReviewStatus(id, status);
        // 业务表数据更新
        tableUpdateContext.executeUpdate(reviewLogDO.getBusinessType(), reviewLogDO.getBusinessId(), status.toString());
        reviewLogDO.setStatus(status);
        if (StringUtils.isNotBlank(reviewMsg)) {
            reviewLogDO.setReviewMsg(reviewMsg);
        }
        reviewLogDO.setOperator(SecurityFrameworkUtils.getLoginUserNickname());
        reviewLogDO.setOperateTime(LocalDateTime.now());
        logMapper.updateById(reviewLogDO);
    }
java 复制代码
package com.ylt.module.operation.strategy;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
public class TableUpdateContext {
    private final Map<String, TableUpdateStrategy> strategyMap;

    @Autowired
    public TableUpdateContext(List<TableUpdateStrategy> strategies) {
        // 将策略列表转换为Map,key为支持的表格类型
        this.strategyMap = strategies.stream()
                .collect(Collectors.toMap(
                        TableUpdateStrategy::getSupportedType,
                        Function.identity()
                ));
    }

    /**
     * 执行表状态更新
     */
    public void executeUpdate(String tableType, Long id, String newStatus) {
        TableUpdateStrategy strategy = strategyMap.get(tableType.toLowerCase());
        if (strategy == null) {
            throw new IllegalArgumentException("不支持的表格类型: " + tableType);
        }
        strategy.updateStatus(id, newStatus);
    }

    /**
     * 获取文件路径
     */
    public Map<String, Object> getFilePath(String tableType, Long id) {
        TableUpdateStrategy strategy = strategyMap.get(tableType.toLowerCase());
        if (strategy == null) {
            throw new IllegalArgumentException("不支持的表格类型: " + tableType);
        }
        return strategy.getFilePath(id);
    }
}
java 复制代码
package com.ylt.module.operation.strategy;

import cn.hutool.core.bean.BeanUtil;
import com.ylt.module.operation.dal.dataobject.company.CompanyDO;
import com.ylt.module.operation.dal.dataobject.contract.ContractDO;
import com.ylt.module.operation.dal.dataobject.reviewLog.BusinessTypeEnum;
import com.ylt.module.operation.dal.mysql.company.CompanyMapper;
import com.ylt.module.operation.enums.BaseConstants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class CompanyStrategy implements TableUpdateStrategy {
    @Resource
    private CompanyMapper companyMapper;

    /**
     * 支持的表格类型
     */
    @Override
    public String getSupportedType() {
        return BusinessTypeEnum.COMPANY.getKey();
    }

    @Override
    public void updateStatus(Long id, String newStatus) {
        CompanyDO companyDO = companyMapper.selectById(id);
        companyDO.setId(id);
        companyDO.setInfoStatus(newStatus);
        // 审核通过,资料全部通过为开户完成,未通过为开户中
        if(StringUtils.equals(newStatus, BaseConstants.ReviewStatus.STATUS_PASS)){
            //判断首营资质状态
            if (StringUtils.equals(companyDO.getFirstStatus(),BaseConstants.ReviewStatus.STATUS_PASS)) {
                companyDO.setCompanyStatus(BaseConstants.ReviewStatus.STATUS_PASS);
            }else {
                //companyDO.setCompanyStatus(BaseConstants.ReviewStatus.STATUS_REVIEWING);
                companyDO.setCompanyStatus(BaseConstants.ReviewStatus.STATUS_PASS);
            }
        }
        companyMapper.updateById(companyDO);
    }

    @Override
    public Map<String, Object>  getFilePath(Long id) {
        CompanyDO companyDO = companyMapper.selectById(id);
        Map<String, Object> map = BeanUtil.beanToMap(companyDO);
        return map;
    }
}

4、总结

java 复制代码
┌─────────────────────────────────────────┐
│              调用方(Controller)        │
└───────────────────┬─────────────────────┘
                    │
                    ▼
┌─────────────────────────────────────────┐
│        TableUpdateContext(上下文)      │
│  ┌─────────────────────────────────┐   │
│  │   strategyMap<String, Strategy> │   │
│  └─────────────────────────────────┘   │
└─────────┬───────────────┬───────────────┘
          │               │
          ▼               ▼
┌─────────────────┐  ┌─────────────────┐
│ CompanyStrategy │  │ ContractStrategy │
│ (单位表逻辑)  │  │ (合同表逻辑)  │
└─────────────────┘  └─────────────────┘
相关推荐
进击的荆棘1 天前
Linux系统——线程同步与互斥
linux·运维·服务器·策略模式·同步·互斥·posix
AlanAshley6 天前
四种镜像文件在各操作系统的使用用法及区别
策略模式·虚拟机
拆房老料7 天前
【第四部分:Agentic 智能体设计模式】17. Agent 路由模式详解:从意图识别到动态模型选择
java·设计模式·ai编程·策略模式
zhangfeng113310 天前
com.apple.quarantine 并不是乱码,而是 macOS Gatekeeper 给下载文件自动打上的“隔离属性
macos·策略模式
lpfasd12311 天前
Ollama 还是 LM Studio:在 24GB 的 M6 Mac 上,我把 Ollama 卸载了
macos·策略模式
福大大架构师每日一题13 天前
ollama v0.40.11发布:macOS原生语音生成上线,d3决策模型正式加入
macos·策略模式
AIex-YH16 天前
发酵罐里点一盏灯:光发酵,正在重算微藻蛋白的成本账
运维·制造·策略模式
snakecy17 天前
macOS 安装 LaTeX 全流程指南:从 MacTeX 到中文排版
macos·策略模式
钱栈up21 天前
从 macOS 切回 Windows,我用 5 个免费工具把 80% 操作习惯搬了回来
windows·macos·策略模式
kunicoding23 天前
C++ 策略模式实战:写一个可以“一键换输出“的日志系统
开发语言·c++·策略模式