直接上课上的例子,我们购物后需要支付,支付方式可以有多种:支付宝,微信...
└── strategy
├── AliPay.java
├── Order.java
├── Payment.java
├── PayState.java
├── PayStrategyTest.java
├── PayType.java
└── WechatPay.java
package com.xh.pattern.strategy;
/**
* Created by root on 3/15/18.
*/
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);
}
}
package com.xh.pattern.strategy;
/**
* Created by root on 3/15/18.
*/
public interface Payment {
public PayState pay(String uid, double amount);
}
package com.xh.pattern.strategy;
/**
* Created by root on 3/15/18.
*/
public enum PayType {
ALI_PAY(new AliPay()),
WECHAT_PAY(new WechatPay());
private Payment payment;
PayType(Payment payment) {
this.payment = payment;
}
public Payment get() {
return this.payment;
}
}
package com.xh.pattern.strategy;
/**
* Created by root on 3/15/18.
*/
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;
}
public String toString() {
return ("支付状态:[" + code + "]," + msg + ",交易详情:" + data);
}
}
package com.xh.pattern.strategy;
/**
* Created by root on 3/15/18.
*/
public class AliPay implements Payment {
@Override
public PayState pay(String uid, double amount) {
System.out.println("欢迎使用支付宝");
System.out.println("查询账户余额,开始扣款");
return new PayState(200,"支付成功",amount);
}
}
package com.xh.pattern.strategy;
/**
* Created by root on 3/15/18.
*/
public class WechatPay implements Payment {
@Override
public PayState pay(String uid, double amount) {
System.out.println("欢迎使用微信支付");
System.out.println("直接从微信红包扣款");
return new PayState(200, "支付成功", amount);
}
}
package com.xh.pattern.strategy;
/**
* Created by root on 3/15/18.
*/
public class PayStrategyTest {
public static void main(String[] args) {
//省略把商品添加到购物车,再从购物车下单
//直接从点单开始
Order order = new Order("1", "20180311001000009", 324.45);
//开始支付,选择微信支付、支付宝、银联卡、京东白条、财付通
//每个渠道它支付的具体算法是不一样的
//基本算法固定的
//这个值是在支付的时候才决定用哪个值
System.out.println(order.pay(PayType.WECHAT_PAY));
}
}