java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot策略模式

SpringBoot如何通过Map实现策略模式

作者:一恍过去

策略模式是一种行为设计模式,它允许在运行时选择算法的行为,在Spring框架中,我们可以利用@Resource注解和Map集合来优雅地实现策略模式,这篇文章主要介绍了SpringBoot如何通过Map实现策略模式,需要的朋友可以参考下

前言

策略模式是一种行为设计模式,它允许在运行时选择算法的行为。在Spring框架中,我们可以利用@Resource注解和Map集合来优雅地实现策略模式。

在Spring框架中,当你使用@Resource注解注入一个Map<String, T>时,Spring会自动将所有类型为T的bean收集到这个Map中,其中:

底层机制解析

Spring的集合类型自动装配

Spring框架对集合类型的依赖注入有特殊处理:

@Resource注解的行为

@Resource注解默认按名称装配,但当目标是一个Map时,Spring会特殊处理:

实现原理

Spring在依赖注入时的处理流程:

使用

直接使用Map<String,T>

我们直接定义一个Controller,并且在Controller中使用@ResourceMap<String,T>

@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    private Map<String, Object> beanMap = new ConcurrentHashMap<>();
    public void beanMap() {
        System.out.println(beanMap.size());
    }
}

验证:
可以看到map中存了项目中所有的bean对象

指定Map中的bean类型

在实际的开发中,我们希望Map中只是存储需要的Bean,并且Controller中可以根据beanName进行转发到不同的Service中,步骤如下:

定义策略接口

public interface PaymentStrategy {
    void pay();
}

定义实现类

@Service("ALI")
	@Slf4j
	public class AliStrategyService implements PaymentStrategy {
	    @Override
	    public void pay() {
	        log.info("使用支付宝支付");
	    }
	}
	@Service("WX")
	@Slf4j
	public class WxStrategyService implements PaymentStrategy {
	    @Override
	    public void pay() {
	        log.info("使用微信支付");
	    }
	}

策略使用

@RestController
@RequestMapping("/test")
public class TestController {
    @Resource
    private Map<String, PaymentStrategy> beanMap = new ConcurrentHashMap<>();
    public void beanMap() {
        PaymentStrategy wx = beanMap.get("WX");
        wx.pay();
        PaymentStrategy ali = beanMap.get("ALI");
        ali.pay();
    }
}

验证

可以看到map中,就只有两个Bean,并且key就是我们通过@Service(value)定义的名称

自定义注解实现

自定义一个注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Component
public @interface PaymentType {
    String value();
}

注解替换:将原有的@Service(value)替换为@PaymentType (value),比如:

@PaymentType("CARD")
@Slf4j
public class CardStrategyService implements PaymentStrategy {
    @Override
    public void pay() {
        log.info("使用银行卡支付");
    }
}

**意义:**可以更好表示策略模式,让其他开发人员一眼可以看出当前的Service使用了策略模式

到此这篇关于SpringBoot通过Map实现天然的策略模式的文章就介绍到这了,更多相关SpringBoot策略模式内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文