在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();
        }
    }
}
相关推荐
格鸰爱童话6 分钟前
向AI学习项目技能(三)
java·人工智能·python·学习
浩宇软件开发10 分钟前
springBoot+Vue中华诗词学习后台管理系统
vue.js·spring boot·axios·element-plus·router
weixin1997010801611 分钟前
南网商城商品详情页前端性能优化实战
java·前端·性能优化
iPadiPhone14 分钟前
Spring Boot 自动装配原理与 Starter 开发实战
java·spring boot·后端·spring·面试
SuGarSJL15 分钟前
FakeSMTP-2.1.1使用
java·maven
码匠君16 分钟前
首个基于 Spring Boot 4 的正式版发布!Dante Cloud 4.X 新特性全解析
java·spring boot·后端
悟空码字26 分钟前
SpringBoot + 百度地图SDK,打造企业级位置服务中台
java·百度·地图·编程技术·后端开发
weixin1997010801628 分钟前
网易考拉商品详情页前端性能优化实战
java·前端·python·性能优化
Natalia_Portman28 分钟前
springboot整合DolphinDB
java·数据库·spring boot·后端·db