美文网首页
三、策略模式

三、策略模式

作者: 奔跑吧老王 | 来源:发表于2020-03-31 15:34 被阅读0次

话不多说先来类图

image.png

支付接口

public interface Payment {
    PayResult pay(Double amount);
}

QQpay

public class QQPay implements Payment {
    @Override
    public PayResult pay(Double amount) {
        System.out.println("欢迎!财付通为你服务");
        System.out.println("支付开始");
        PayResult payResult = new PayResult(200,"财付通支付成功","成功扣款"+amount);
        return  payResult;
    }
}

UnionPay

public class UnionPay implements Payment {
    @Override
    public PayResult pay(Double amount) {
        System.out.println("欢迎!银联支付为你服务");
        System.out.println("支付开始");
        PayResult payResult = new PayResult(200,"银联支付成功","成功扣款"+amount);
        return payResult;
    }
}

AliPay

public class AliPay implements Payment {
    @Override
    public PayResult pay(Double amount) {
        System.out.println("欢迎!支付宝支付为你服务");
        System.out.println("支付开始");
        PayResult payResult = new PayResult(200,"支付宝,支付成功","成功扣款"+amount);
        return payResult;
    }
}

WechatPay

public class WechatPay implements Payment {
    @Override
    public PayResult pay(Double amount) {
        System.out.println("欢迎!微信红包支付为你服务");
        System.out.println("支付开始");
        PayResult payResult = new PayResult(200,"微信红包支付成功","成功扣款"+amount);
        return payResult;
    }
}

支付结果封装

public class PayResult {

    private Integer status;
    private String msg;
    private Object object;

    public PayResult(Integer status, String msg, Object object) {
        this.status = status;
        this.msg = msg;
        this.object = object;
    }

    @Override
    public String toString() {
        return "PayResult{" +
                "status=" + status +
                ", msg='" + msg + '\'' +
                ", object=" + object +
                '}';
    }
}

上下文封装

public class Order {
    private Long orderId;
    private String orderList;
    private Double amount;

    public Order(Long orderId, String orderList, Double amount) {
        this.orderId = orderId;
        this.orderList = orderList;
        this.amount = amount;
    }

    public PayResult pay(Payment payment){
        PayResult payResult = payment.pay(amount);
        return payResult;
    }
}

支付类型封装

public enum PayTypeEnum {
    AliPay(new AliPay()),WechatPay(new WechatPay()),UnionPay(new UnionPay()),QQPay(new QQPay());
    private Payment payment;

    PayTypeEnum(Payment payment){
        this.payment = payment;
    }

    public Payment get(){
        return this.payment;
    }
}

具体调用

public class ClientV2 {
    public static void main(String[] args) {
        Order order = new Order(888888L,"huawei,xiaomi",38899.99);
        PayResult result = order.pay(PayTypeEnum.AliPay.get());
        System.out.println(result.toString());
    }
}

最完善的策略模式,如果感觉还可以请点击关注,您的支持是作者创作的最大动力,谢谢老铁!!!

相关文章

网友评论

      本文标题:三、策略模式

      本文链接:https://www.haomeiwen.com/subject/htlauhtx.html