我们先做一个订单状态类:
public class PayState {
private int code;
private Object data;
private String msg;
public PayState(int code, String msg,Object data) {
this.code = code;
this.data = data;
this.msg = msg;
}
@Override
public String toString(){
return ("支付状态:[" + code + "]," + msg + ",交易详情:" + data);
}
}
然后来一个订单类:
public class Order {
private String uid;
private String orderId;
private double amount;
public Order(String uid,String orderId,double amount){
this.uid = uid;
this.orderId = orderId;
this.amount = amount;
}
//这个参数,完全可以用Payment这个接口来代替
//为什么?
//完美地解决了switch的过程,不需要在代码逻辑中写switch了
//更不需要写if else if
public PayState pay(PayType payType){
return payType.get().pay(this.uid,this.amount);
}
}
枚举支付类型:
public enum PayType {
ALI_PAY(new AliPay()),
WECHAT_PAY(new WechatPay()),
UNION_PAY(new UnionPay()),
JD_PAY(new JDPay());
private Payment payment;
PayType(Payment payment){
this.payment = payment;
}
public Payment get(){return this.payment;}
}
支付渠道接口:
public interface Payment {
public PayState pay(String uid, double amount);
}
来几个不同的支付方式:
public class WechatPay implements Payment {
public PayState pay(String uid, double amount) {
System.out.println("欢迎使用微信支付");
System.out.println("直接从微信红包扣款");
return new PayState(200,"支付成功",amount);
}
}
再来一个:
public class AliPay implements Payment {
public PayState pay(String uid, double amount) {
System.out.println("欢迎使用支付宝");
System.out.println("查询账户余额,开始扣款");
return new PayState(200,"支付成功",amount);
}
}
还有呢:
public class JDPay implements Payment {
public PayState pay(String uid, double amount) {
System.out.println("欢迎使用京东白条");
System.out.println("查询账户余额,开始扣款");
return new PayState(200,"支付成功",amount);
}
}
再来一个:
public class UnionPay implements Payment {
public PayState pay(String uid, double amount) {
System.out.println("欢迎使用银联卡支付");
System.out.println("查询账户余额,开始扣款");
return new PayState(200,"支付成功",amount);
}
}
可以了,我们来测试:
public static void main(String[] args) {
//省略把商品添加到购物车,再从购物车下单
//直接从点单开始
Order order = new Order("1","20180311001000009",324.45);
//开始支付,选择微信支付、支付宝、银联卡、京东白条、财付通
//每个渠道它支付的具体算法是不一样的
//基本算法固定的
//这个值是在支付的时候才决定用哪个值
System.out.println(order.pay(PayType.WECHAT_PAY));
}