策略模式实战

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 │
│ (单位表逻辑)  │  │ (合同表逻辑)  │
└─────────────────┘  └─────────────────┘
相关推荐
张小姐的猫9 小时前
【Linux】网络编程 —— HTTP协议(上)
linux·运维·服务器·网络·http·单例模式·策略模式
笨拙的老猴子7 天前
小明学架构师的第七课:策略模式:告别if-else的选择困难症
系统架构·策略模式
肖爱Kun7 天前
C++设计策略模式
开发语言·c++·策略模式
折哥的程序人生 · 物流技术专研9 天前
Java 23 种设计模式:从踩坑到精通 | 番外:策略 vs 模板方法 —— 组合与继承的终极对决
java·策略模式·java面试·comparator·模版方法模式·java设计模式·从踩坑到精通
折哥的程序人生 · 物流技术专研9 天前
Java 23 种设计模式:从踩坑到精通 | 番外:状态 vs 策略 —— if-else 消除的两条路,你走对了吗?
java·spring·状态模式·策略模式·java面试·java设计模式·从踩坑到精通
ttod_qzstudio11 天前
【软考设计模式】策略模式:算法族的封装与动态切换精讲
设计模式·策略模式
儒雅的名12 天前
GoF设计模式——策略模式
设计模式·bash·策略模式
折哥的程序人生 · 物流技术专研12 天前
第4篇:Lambda 简化策略模式(Java 8+)
java·设计模式·策略模式·函数式编程·lambda·代码简化·扩充系列
在水一缸13 天前
拒绝被打扰:深度解析 macOS 进程守护与“反自动启动”攻防战
macos·策略模式·用户体验·进程守护·自动启动·系统权限
折哥的程序人生 · 物流技术专研13 天前
第3篇:手写促销策略引擎(满减、打折、立减)
java·设计模式·策略模式·开闭原则·编程实战·扩充系列·促销引擎