行为行模式
根据用户的需求处理对封装好的算法做出选择。
解决在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。
类图:
1、创建一个支付接口:
public interface Payment {
public PayState pay(String uid,double amount);
}
2、实现接口:
public class AliPay implements Payment {
@Override
public PayState pay(String uid, double amount) {
System.out.println("使用支付宝支付");
System.out.println("一顿操作");
return new PayState(200,"支付成功",amount);
}
}
public class WeChatPay implements Payment {
@Override
public PayState pay(String uid, double amount) {
System.out.println("使用微信支付");
System.out.println("一顿操作");
return new PayState(200,"支付成功",amount);
}
}
public class UnionPay implements Payment {
@Override
public PayState pay(String uid, double amount) {
System.out.println("使用银联卡支付");
System.out.println("一顿操作");
return new PayState(200,"支付成功",amount);
}
}
3、支付方式的枚举类:
public enum PayType {
ALI_PAY(new AliPay()),
WECHART_PAY(new WeChatPay()),
UNION_PAY(new UnionPay());
private Payment payment;
PayType(Payment payment) {
this.payment = payment;
}
public Payment getPayment(){
return this.payment;
}
}
4、支付订单:
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;
}
public PayState pay(PayType payType){
return payType.getPayment().pay(this.uid,this.amount);
}
}
5、返回支付结果的封装:
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);
}
}
6、测试:
public static void main( String[] args )
{
//加入购物车
//。。。。中间省略
//下单
Order order = new Order("1","21080803000001",100d);
//开始支付,微信,银联卡
System.out.println(order.pay(PayType.ALI_PAY));
//System.out.println(order.pay(PayType.WECHART_PAY));
//System.out.println(order.pay(PayType.UNION_PAY));
}
7、输出:
使用支付宝支付
一顿操作
支付状态,[200],支付成功,交易详情:100.0