1、策略模式公共接口类
BankFileStrategy
java
public interface BankFileStrategy {
String getBankFile(String bankType) throws Exception;
}
2、策略模式业务实现类
java
@Slf4j
@Component
public class ConcreteStrategy implements BankFileStrategy {
@Override
public String getBankFile(String bankType) throws Exception {
....业务代码
}
3、策略模式实现类枚举
java
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、策略模式执行类
java
@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、测试策略模式
java
@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";
}
}
}