1、策略模式公共接口类
- public interface BankFileStrategy {
-
- String getBankFile(String bankType) throws Exception;
- }
复制代码 2、策略模式业务实现类
- @Slf4j
- @Component
- public class ConcreteStrategy implements BankFileStrategy {
-
- @Override
- public String getBankFile(String bankType) throws Exception {
- ....业务代码
- }
复制代码 3、策略模式实现类摆列
- public enum BankTypeClassEnum {
- //
- strategyA("ICBC", "concreteStrategy"),
- ;
- private String name;
- private String implName;
- public static String getImplName(String name) {
- if (StringUtils.isBlank(name)) {
- return null;
- }
- for (BankTypeClassEnum aEnum : BankTypeClassEnum.values()) {
- if (aEnum.getName().equals(name)) {
- return aEnum.getImplName();
- }
- }
- return null;
- }
- BankTypeClassEnum(String name, String implName) {
- this.name = name;
- this.implName = implName;
- }
- public String getName() {
- return name;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getImplName() {
- return implName;
- }
- public void setImplName(String implName) {
- this.implName = implName;
- }
- }
复制代码 4、策略模式实行类
- @Slf4j
- @Component
- public class BankFileContext {
- //当一个接口有多个实现类时,Spring会自动将Strategy接口的实现类注入到这个Map中,key为bean id,value值则为对应的策略实现类
- @Autowired
- private Map<String, BankFileStrategy> bankFileStrategyMap;
- /**
- * 执行类
- */
- public String execute(String bankType) throws Exception {
- BankFileStrategy service = bankFileStrategyMap.get(BankTypeClassEnum.getImplName(bankType));
- return service.getBankFile(bankType);
- }
- }
复制代码 5、测试策略模式
- @Slf4j
- @RestController
- @RequiredArgsConstructor(onConstructor = @__(@Autowired))
- public class TestBankFileController {
- private final BankFileContext bankFileContext;
-
- @GetMapping(value = "/bank/{bankType}/file")
- public String testBankFile(@PathVariable String bankType) {
- try {
-
- return bankFileContext.execute(bankType);
- } catch (Exception e) {
- log.error("testBankFile is error", e);
- return "error";
- }
- }
- }
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |