spring实现策略模式的几个方式

类级别

@Component
public class RenewmsgSenderContext implements ApplicationContextAware {

    Map<String, RenewMsgSenderStrategy> actionRenewSenderMappings =  Maps.newConcurrentMap();
    
    private ApplicationContext applicationContext;
    
    public static final String noOperateDemandMSgSenderStr = "noOperateDemandMSgSender";
    public static final String  noRenewOpinionMsgSenderStr = "noRenewOpinionMsgSender";
    @PostConstruct
    public void init() {
        NoOperateDemandMSgSender noOperateDemandMSgSender = applicationContext.getBean(NoOperateDemandMSgSender.class);
        NoRenewOpinionMsgSender noRenewOpinionMsgSender = applicationContext.getBean(NoRenewOpinionMsgSender.class);
        actionRenewSenderMappings.put(noOperateDemandMSgSenderStr,noOperateDemandMSgSender);
        actionRenewSenderMappings.put(noRenewOpinionMsgSenderStr,noRenewOpinionMsgSender);
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 通过类型获取方法
     *
     * @param
     * @return
     */
    public RenewMsgSenderStrategy getSender(String type) {
        return actionRenewSenderMappings.get(type);
    }

方法级别

@Component
public class CopyrightExpireShowUpdateServiceFunction implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    public static final String updateOfflineOpinion = "updateOfflineOpinion";
    public static final String updateOperateDemandOpinion = "updateOperateDemandOpinion";
    public static final String updateRenewFeedback = "updateRenewFeedback";

    Map<String, Function<UpdateOptionParams, Integer>> actionUpdateMappings =  Maps.newConcurrentMap();


    @PostConstruct
    public void init() {
        CopyrightExpireService copyrightExpireService = applicationContext.getBean(CopyrightExpireService.class);
        actionUpdateMappings.put(updateOfflineOpinion,(someParams)->copyrightExpireService.updateOfflineOpinion(someParams));
        actionUpdateMappings.put(updateOperateDemandOpinion,(someParams)->copyrightExpireService.updateOperateDemandOpinion(someParams));
        actionUpdateMappings.put(updateRenewFeedback,(someParams)->copyrightExpireService.updateRenewFeedback(someParams));
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 通过类型获取方法
     *
     * @param
     * @return
     */
    public Integer updateOfflineOpinion(UpdateOptionParams params) {
        return actionUpdateMappings.get(params.getType()).apply(params);
    }

静态方法配置

public interface IGiftInfoStrategyService {

    GiftInfo getGiftInfo(int activityId);
}

/**
 * 双11活动
 */
@Service
public class DoubleElevenGiftInfoStrategyService implements IGiftInfoStrategyService {

    // 静态代码块中注册关联
    static {
        GiftInfoContext.registerProvider(2, DoubleElevenGiftInfoStrategyService.class);
    }

    @Override
    public GiftInfo getGiftInfo(int activityId) {
        // 双11调用统一平台接口获取礼品信息
        GiftInfo giftInfo = new GiftInfo();
        giftInfo.setGiftId(902);
        giftInfo.setGiftName("空气净化器");
        return giftInfo;
    }
}

/**
 * 夏季购车节
 */
@Service
public class SummerBuyDayGiftInfoStrategyService implements IGiftInfoStrategyService {

    // 静态代码块中注册关联
    static {
        GiftInfoContext.registerProvider(1, SummerBuyDayGiftInfoStrategyService.class);
    }

    @Resource
    private GiftInfoMapper giftInfoMapper;
    
    public GiftInfo getGiftInfo(int activityId) {
        // 从数据库中查询
        GiftInfo giftInfo = new GiftInfo();
        giftInfo.setGiftId(1);
        giftInfo.setGiftName("铁锅三件套");
        giftInfoMapper.getGiftInfoByActivityId(activityId)
        return giftInfo;
    }
}

/**
 * 礼品信息环境角色类
 */
@Component
public class GiftInfoContext {

    private static final Logger logger = LoggerFactory.getLogger(GiftInfoContext.class);

    // 策略映射map
    private static final Map<Integer, Class<?>> providers = new HashMap<>();

    // 提供给策略具体实现类的注册返回
    public static void registerProvider(int subjectId, Class<?> provider) {
        providers.put(subjectId, provider);
    }

    // 对外暴露的获取礼品信息接口返回
    public static GiftInfo getGiftInfo(int subjectId, int activityId) {
        Class<?> providerClazz = providers.get(subjectId);
        Assert.assertNotNull(providerClazz);
        Object bean = SpringUtils.getBean(providerClazz);
        Assert.assertNotNull(bean);
        if (bean instanceof IGiftInfoStrategyService) {
            IGiftInfoStrategyService strategyService = (IGiftInfoStrategyService) bean;
            return strategyService.getGiftInfo(activityId);
        }
        logger.error("Not Class with IGiftInfoListService: {}", providerClazz.getName());
        return null;
    }
}

public class GiftInfoTest {

    public GiftInfo getGiftInfo(int subjectId, int activityId) {
        GiftInfo giftInfo = GiftInfoContext.getGiftInfo(subjectId, activityId);
        Assert.assertNotNull(giftInfo);
        return giftInfo;
    }
}

spring配置注入

public interface IGiftInfoStrategyService {

    GiftInfo getGiftInfo(int activityId);
    int typeId();
}

/**
 * 夏季购车节
 */
@Service
public class SummerBuyDayGiftInfoStrategyService implements IGiftInfoStrategyService {

    @Resource
    private GiftInfoMapper giftInfoMapper;
    
    public GiftInfo getGiftInfo(int activityId) {
        // 从数据库中查询
        GiftInfo giftInfo = new GiftInfo();
        giftInfo.setGiftId(1);
        giftInfo.setGiftName("铁锅三件套");
        giftInfoMapper.getGiftInfoByActivityId(activityId)
        return giftInfo;
    }

    @Override
    public int typeId() {
        return 1;
    }
}

/**
 * 双11活动
 */
@Service
public class DoubleElevenGiftInfoStrategyService implements IGiftInfoStrategyService {

    @Override
    public GiftInfo getGiftInfo(int activityId) {
        // 双11调用统一平台接口获取礼品信息
        GiftInfo giftInfo = new GiftInfo();
        giftInfo.setGiftId(902);
        giftInfo.setGiftName("空气净化器");
        return giftInfo;
    }

    @Override
    public int typeId() {
        return 2;
    }
}

package com.shawntime.designpattern.strategy.example;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

/**
 * 礼品信息环境角色类
 */
@Component
public class GiftInfoContext implements ApplicationListener<ContextRefreshedEvent> {

    /**
     * 注入的策略
     */
    private Map<Integer, IGiftInfoStrategyService> giftInfoStrategyServiceMap = new HashMap<>();

    /**
     * 对外暴露的统一获取礼品信息的返回
     */
    public GiftInfo getGiftInfo(int typeId, int activityId) {
        IGiftInfoStrategyService giftInfoStrategyService = giftInfoStrategyServiceMap.get(typeId);
        Assert.assertNotNull(giftInfoStrategyService);
        return giftInfoStrategyService.getGiftInfo(activityId);
    }

    public Map<Integer, IGiftInfoStrategyService> getGiftInfoStrategyServiceMap() {
        return giftInfoStrategyServiceMap;
    }

    public void setGiftInfoStrategyServiceMap(Map<Integer, IGiftInfoStrategyService> giftInfoStrategyServiceMap) {
        this.giftInfoStrategyServiceMap = giftInfoStrategyServiceMap;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
        if (applicationContext.getParent() == null) {
            Map<String, IGiftInfoStrategyService> infoStrategyServiceMap =
                    applicationContext.getBeansOfType(IGiftInfoStrategyService.class);
            infoStrategyServiceMap.values()
                    .forEach(strategyService -> {
                        int typeId = strategyService.typeId();
                        giftInfoStrategyServiceMap.put(typeId, strategyService);
                    });

        }
    }
}


/**
 * 礼品信息配置类
 */
@ComponentScan("com.shawntime.designpattern.strategy.example")
@Configuration
public class GiftInfoConfig {

}

/**
 * 礼品信息调用
 */
public class GiftInfoTest {

    private AnnotationConfigWebApplicationContext context;

    @Before
    public void before() {
        context = new AnnotationConfigWebApplicationContext();
        context.register(GiftInfoConfig.class);
        context.refresh();
    }

    @Test
    public void getGiftInfo() {
        GiftInfoContext giftInfoContext = context.getBean(GiftInfoContext.class);
        GiftInfo giftInfo = giftInfoContext.getGiftInfo(1, 2);
        Assert.assertNotNull(giftInfo);
    }
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用Spring框架实现策略模式的示例: 首先,定义一个策略接 `Strategy`,包含一个 `execute()` 方法: ```java public interface Strategy { void execute(); } ``` 然后,创建几个具体的策略类实现该接口: ```java @Component public class StrategyA implements Strategy { @Override public void execute() { System.out.println("执行策略A"); } } @Component public class StrategyB implements Strategy { @Override public void execute() { System.out.println("执行策略B"); } } @Component public class StrategyC implements Strategy { @Override public void execute() { System.out.println("执行策略C"); } } ``` 接下来,创建一个策略上下文类 `StrategyContext`,并使用Spring的依赖注入功能将所有的策略类注入进来: ```java @Component public class StrategyContext { private final Map<String, Strategy> strategyMap; public StrategyContext(List<Strategy> strategies) { this.strategyMap = strategies.stream().collect(Collectors.toMap(Strategy::getClass.getSimpleName, Function.identity())); } public void executeStrategy(String strategyName) { Strategy strategy = strategyMap.get(strategyName); if (strategy != null) { strategy.execute(); } else { throw new IllegalArgumentException("Unsupported strategy: " + strategyName); } } } ``` 最后,在其他需要使用策略模式的地方,可以通过依赖注入 `StrategyContext` 对象,并调用其 `executeStrategy()` 方法执行相应的策略: ```java @Component public class SomeService { private final StrategyContext strategyContext; public SomeService(StrategyContext strategyContext) { this.strategyContext = strategyContext; } public void doSomething(String strategyName) { strategyContext.executeStrategy(strategyName); } } ``` 这样,通过使用Spring框架的依赖注入功能,我们可以方便地在运行时动态切换不同的策略实现
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值