java(Springboot)实现策略模式

依赖包如下:

   
            org.springframework.boot
            spring-boot-starter-web
        
        
            org.springframework.boot
            spring-boot-starter-aop
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            com.alibaba
            fastjson
            2.0.19
        
        
            org.apache.commons
            commons-lang3
            3.9
        

策略要处理的接口AppService 

public interface AppService {
    public String doService();
}

接口实现类AndoridServiceImpl和IosServiceImpl

@Log4j2
@Service("andoridService")
public class AndoridServiceImpl implements AppService{
    @Override
    public String doService() {
       log.info("do AndoridService");
       return "Andorid";
    }
}
@Log4j2
@Service("iosService")
public class IosServiceImpl implements AppService{
    @Override
    public String doService() {
        log.info("do IosService");
        return "Ios";
    }
}

策略选择类StrategyDispatch,注意这里用到注解  @Qualifier,建议配套着Service("value")一起使用

@Service
public class StrategyDispatch {
    @Qualifier("iosService")
    @Resource
    private AppService iosService;
    @Qualifier("andoridService")
    @Resource
    private AppService andoridService;
    public AppService getAppServiceByType(String type){
        if(StringUtils.equals(type,"ios")){
            return iosService;
        }else if(StringUtils.equals(type,"andorid")){
            return andoridService;
        }
        return null;
    }
}

调用类StrategyController

@RestController
@RequestMapping("/strategy")
public class StrategyController {
    @Resource
    private StrategyDispatch strategyDispatch;
    @GetMapping("getServiceByType/{type}")
    public String  getUserInfoByUser(@PathVariable("type") String type){
        return strategyDispatch.getAppServiceByType(type).doService();
    }
}

Postman调用:

java(Springboot)实现策略模式_第1张图片

java(Springboot)实现策略模式_第2张图片 

 控制台打印:

java(Springboot)实现策略模式_第3张图片

 

你可能感兴趣的:(springboot,java,java,spring,boot,开发语言)