封装,包装的使用
1.通用对象PriceRequest
public class PriceRequest {
protected String regionId;
protected int count;
protected String pinAlias;
protected ApplyType applyType;
public ApplyType getApplyType() {
return applyType;
}
public void setApplyType(ApplyType applyType) {
this.applyType = applyType;
}
public String getPinAlias() {
return pinAlias;
}
public void setPinAlias(String pinAlias) {
this.pinAlias = pinAlias;
}
public String getRegionId() {
return regionId;
}
public void setRegionId(String regionId) {
this.regionId = regionId;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
2.接口CalculateTotalPrice 加泛型,功能是获取不同产品的价格,产品有redis,pod
public interface CalculateTotalPrice<T extends PriceRequest> {
Number calculate(T info);
}
3.依赖redis的对象
public class RedisPriceRequest extends PriceRequest {
private String instanceType;
public String getInstanceType() {
return instanceType;
}
public void setInstanceType(String instanceType) {
this.instanceType = instanceType;
}
}
4.接口实现类
public class RedisCalculatePrice extends AbstractPrice implements CalculateTotalPrice<RedisPriceRequest> {
private static final Logger logger = LoggerFactory.getLogger(RedisCalculatePrice.class);
private static final String SERVICE_CODE = "redis";
private final BillingClientHolder clientHolder;
public RedisCalculatePrice() {
this.clientHolder = BeanContext.getBean(BillingClientHolder.class);
}
@Override
public Number calculate(RedisPriceRequest info) {
FamaPin pin = getPin(info.getPinAlias());
CalculateTotalPriceRequest request = buildParam(info);
CalculateTotalPriceResponse response = null;
try {
response = clientHolder.getClientByPin(pin).calculateTotalPrice(request);
if (null == response.getResult()) {
logger.error("get price has error :{}", response.getError().getMessage());
return 0;
}
return response.getResult().getDiscountedTotalPrice();
} catch (Exception ex) {
logger.warn("query billing from jcloud failed", ex);
logger.warn("request is {}, respond is {}", JsonUtils.toJSONString(request), JsonUtils.toJSONString(response));
return 0;
}
}
}
5.实现类的再次封装
public class PriceServiceControl<T extends PriceRequest> {
private final CalculateTotalPrice<T> price;
public PriceServiceControl(CalculateTotalPrice<T> price) {
this.price = price;
}
public Number calculate(T couponInfo) {
return price.calculate(couponInfo);
}
}
6.最终代码调用
PriceServiceControl<RedisPriceRequest> redisControl = new PriceServiceControl<>(new RedisCalculatePrice());
price = redisControl.calculate(redisPriceRequest);
原创:做时间的朋友