比如我们有一个接口。
public interface EnPayService {
public GenericResponse enpay(int tenantId, long punitId, String iden, double chargeMoney);
}
3个实现类
@Service(PayType.Names.EN_PAY_BOC)
public class BocPayServiceImpl implements EnPayService {
@Override
public GenericResponse enpay(int tenantId, long punitId, String iden, double chargeMoney) {
return null;
}
}
@Service(PayType.Names.EN_PAY_CCB)
public class CcbServiceImpl implements EnPayService {
@Override
public GenericResponse enpay(int tenantId, long punitId, String iden, double chargeMoney) {
return null;
}
}
@Service(PayType.Names.EN_PAY_ICBC)
public class IcbcServiceImpl implements EnPayService {
@Override
public GenericResponse enpay(int tenantId, long punitId, String iden, double chargeMoney) {
return null;
}
}
这里我们使用枚举来管理的bean的名称,这样我们可以在需要使用的时候,直接从枚举里面获取
public enum PayType {
CCB(8, Names.EN_PAY_CCB), // 建行支付
ICBC(11, Names.EN_PAY_ICBC), // 工行支付
BOC(15, Names.EN_PAY_BOC); // 中行支付
public class Names {
public static final String EN_PAY_CCB = "enpay_ccb";
public static final String EN_PAY_ICBC = "enpay_icbc";
public static final String EN_PAY_BOC = "enpay_boc";
}
private int code;
private String name;
public static PayType resolve(int code) {
for (PayType t : PayType.values()) {
if (t.getCode() == code) {
return t;
}
}
return CCB;
}
private PayType(int code, String name) {
this.code = code;
this.name = name;
}
public int getCode() {
return code;
}
public String getName() {
return name;
}
}
然后就可以创建我们的工厂类了
@Service
public class ExtPayFactory{
@Autowired
private Map service = new ConcurrentHashMap<>();
public EnPayService enpay(PayType payType) {
return service.get(payType.getName());
}
}
使用枚举,可以更好的管理bean的名称,让我们在工厂里面可以更直观的拿到相关bean的名称