接口
public interface Pay {
public abstract String pay();
}
抽象类
public abstract class AbstractPay implements Pay {
}
实现类
@Service
public class Alipay extends AbstractPay {
@Override
public String pay() {
System.out.println("alipay service");
return "alipay";
}
}
@Service
public class Wxpay extends AbstractPay {
@Override
public String pay() {
System.out.println("wxpay service");
return "wxpay";
}
}
枚举类
public enum PayEnum {
ALIPAY(1, "Alipay"),
WXPAY(2, "Wxpay");
public Integer code;
public String serviceName;
PayEnum(Integer code, String serviceName) {
this.code = code;
this.serviceName = serviceName;
}
public static PayEnum getPayForServiceName(String name) {
PayEnum[] values = values();
for (int i = 0; i < values.length; i++) {
if (values[i].serviceName.equals(name)) {
return values[i];
}
}
return null;
}
}
入口,调度
@RestController
@RequestMapping("pay")
public class PayController {
private Map<Integer, Pay> payMap = null;
public PayController(List<Pay> pays) {
payMap = new HashMap<>();
for (Pay pay : pays) {
PayEnum payForServiceName = PayEnum.getPayForServiceName(pay.getClass().getSimpleName());
if (null != payForServiceName) {
payMap.put(payForServiceName.code, pay);
}
}
}
@GetMapping("/{code}")
public String toPay(@PathVariable Integer code) {
return payMap.get(code).pay();
}
}
这只是一个简单的小案例,需要优化,另外也可以组合其他的设计模式