在springboot项目中使用策略工厂模式

在springboot项目中使用策略工厂模式

策略接口类

java 复制代码
package cn.test.ext;

public interface ITestStrategy {

    void execTestMethod();
}

策略实现类

java 复制代码
package cn.test.ext.beanlife;

import cn.test.ext.ITestStrategy;
import cn.test.ext.MyStrategyFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

/**
 * InitializingBean
 * 实现该接口,你的bean可以在 spring容器初始化当前bean时 执行自定义逻辑
 *
 * 必须在afterPropertiesSet方法里写你自定义的执行逻辑
 */
@Slf4j
@Component
public class TestInitializingBean implements ITestStrategy, InitializingBean {

    private static String str ;

    //实现InitializingBean接口,必须重写afterPropertiesSet方法
    //这样当springboot启动加载TestInitializingBean时,会自动执行里边的afterPropertiesSet方法
    @Override
    public void afterPropertiesSet() throws Exception {
        //本方法里可以做一些初始化的操作,如设置类静态变量值 / 将类注册到策略工厂/ 执行一些其他方法或动作/...

        //设置类静态变量值
        str = "qwe123!";

        //将k1策略 (本类) 注册到 策略工厂里
        MyStrategyFactory.register("k1",this);
        log.info("注册了策略:{}到策略工厂里",this);
    }

    @Override
    public void execTestMethod() {
        log.info("start----执行k1策略...");

        System.err.println(str);
    }
}

策略工厂类

java 复制代码
package cn.test.ext;

import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 策略工厂
 */
@Component
@Slf4j
public class MyStrategyFactory {

    private static Map<String, ITestStrategy> strategyMap = new ConcurrentHashMap<>();


    /**
     * 将每个策略注册到策略工厂
     *
     * 利用策略类里的 InitializingBean 的afterPropertiesSet方法,
     * 来把策略类初始化到StrategyFactory 策略工厂里
     *
     * @param strategyCode String
     * @param itemStrategy IPersonAddrSimilarComputeHandleStrategy
     */
    public static void register(String strategyCode, ITestStrategy itemStrategy) {
        strategyMap.put(strategyCode, itemStrategy);
    }

    /**
     * 从策略工厂取出需要的策略
     * @param key
     * @return
     */
    public static ITestStrategy getReceiptHandleStrategy(String key) {
        for (String strate : strategyMap.keySet()) {
            if (StrUtil.equals(strate, key)) {
                //按key取出对应的策略类,来执行处理策略
                ITestStrategy strategy = strategyMap.get(key);
                log.info("拿到了策略:{}", strategy.getClass().getName());
                return strategy;
            }
        }
        log.info("没拿到对应的策略类,不存在 策略:{}", key);
        return null;
    }
}

策略上下文类

java 复制代码
package cn.test.ext;

import org.springframework.stereotype.Component;

@Component
public class MyStrategyContext {

    private ITestStrategy iTestStrategy;

    //1.按key get某个策略类
    public void getStrategyInstance(String key) {
        ITestStrategy strategyInstance = MyStrategyFactory.getReceiptHandleStrategy(key);
        this.iTestStrategy = strategyInstance;
    }

    //2.通过context执行该策略类里的方法
    public void execMethod(){
        if (iTestStrategy!=null){
            iTestStrategy.execTestMethod();
        }
    }
}
相关推荐
用户3721574261358 分钟前
如何使用 Java 在 Word 文档中添加和删除水印:分步指南
java
王中阳Go1 小时前
老板用AI三天写到90%,让我明天上线:Java 团队怎么接这10%的烂摊子?
java
gugucoding2 小时前
55. 【Java】Maven:项目构建的“管家”
java·maven
郑州光合科技余经理2 小时前
海外版多语言团购系统架构:主数据互通与核销边界
java·开发语言·前端·后端·系统架构·php·ai编程
Jesse_EC3 小时前
为什么我设置的 contentLength 到了消费端变成了 0?
java
vipxieliang3 小时前
ValidX 的 Date 和 DateTime vs JPA 的 Temporal 对比
java·后端
杜touch3 小时前
Spring框架的AnnotationConfigApplicationContext类启动的流程
java
AI人工智能+电脑小能手4 小时前
大白话说Java设计模式-26-策略模式(业务实战篇)
java·spring·设计模式·策略模式·支付系统·算法切换
不是光头 强4 小时前
Java 后端 AI 技术选型与学习路线
java·人工智能·学习