1、定义公共的接口
/**
* @ClassName: StrategyModeService
* @Version: 1.0
*/
public interface StrategyModeService {
String strategyModeTest();
}
2、定义实现类
/**
* 服务一
* @ClassName: OneServiceImpl
* @Version: 1.0
*/
@Service
public class OneServiceImpl implements StrategyModeService {
@Override
public String strategyModeTest() {
return "one-service";
}
}
/**
* 服务二
* @ClassName: TwoServiceImpl
* @Version: 1.0
*/
@Service
public class TwoServiceImpl implements StrategyModeService {
@Override
public String strategyModeTest() {
return "two-service";
}
}
/**
* 服务三
* @ClassName: ThreeServiceImpl
* @Version: 1.0
*/
@Service
public class ThreeServiceImpl implements StrategyModeService {
@Override
public String strategyModeTest() {
return "three-service";
}
}
3、定义枚举类
/**
* @ClassName: ServiceTypeEnum
* @Version: 1.0
*/
@Getter
@AllArgsConstructor
public enum ServiceTypeEnum {
//
ONE(1, new OneServiceImpl()),
TWO(2, new TwoServiceImpl()),
THREE(3, new ThreeServiceImpl());
private Integer value;
private StrategyModeService service;
public static StrategyModeService findType(Integer value) {
return Arrays.stream(values()).filter(type -> type.getValue().equals(value)).findFirst().orElse(null).getService();
}
}
4、通过接口调用
/**
* @ClassName: StrategyModeController
* @Version: 1.0
*/
@RestController
@RequestMapping("/strategy/mode")
@Api(value = "策略模式测试", tags = "策略模式测试")
public class StrategyModeController {
@GetMapping("/test")
@ApiOperation("策略模式测试接口")
public String strategyModeTest(int value) {
return ServiceTypeEnum.findType(value).strategyModeTest();
}
}
结果