策略模式
策略模式,又叫政策模式,它是将定义的算法家族分别封装起来,让他们之间可以互相替换,从而让算法的变化不会影响到使用算法的用户,属于行为型模式。
角色:
- 上下文角色(Context):用来操作策略的上下文环境,屏蔽高层模块对策略,算法的直接访问,封装可能存在的变化。
- 抽象策略角色(Strategy):规定策略或算法的行为。
- 具体策略角色(ConcreteStrategy):具体的策略或算法实现。
举例:购物时的支付方式
接口返回封装:
package com.jdwa.strategy;
public class MsgResult {
private int code;
private Object data;
private String msg;
public MsgResult(int code, Object data, String msg) {
this.code = code;
this.data = data;
this.msg = msg;
}
@Override
public String toString() {
return "MsgResult{" +
"code=" + code +
", data=" + data +
", msg='" + msg + '\'' +
'}';
}
}
抽象策略角色:支付方式抽象
package com.jdwa.strategy;
public abstract class Payment {
public abstract String getName();
public MsgResult pay(String uid,double amount){
if (queryBalance(uid) < amount) {
return new MsgResult(500,"支付失败","余额不足");
}
return new MsgResult(200,"支付成功","支付金额"+amount);
}
protected abstract double queryBalance(String uid);
}
具体策略角色:支付宝
package com.jdwa.strategy;
public class AliPay extends Payment{
@Override
public String getName() {
return "支付宝";
}
@Override
protected double queryBalance(String uid) {
return 900;
}
}
具体策略角色:微信
package com.jdwa.strategy;
public class WechatPay extends Payment{
@Override
public String getName() {
return "微信";
}
@Override
protected double queryBalance(String uid) {
return 500;
}
}
上下文:支付策略管理
package com.jdwa.strategy;
import java.util.HashMap;
import java.util.Map;
public class PayStrategy {
public static final String ALI_PAY = "AliPay";
public static final String WECHAT_PAY = "Wechat_pay";
public static final String DEFAULT_PAY = ALI_PAY;
private static Map<String,Payment> strategy = new HashMap<>();
static {
strategy.put(ALI_PAY,new AliPay());
strategy.put(WECHAT_PAY,new WechatPay());
}
public static Payment get(String paykey){
if (!strategy.containsKey(paykey)){
return strategy.get(DEFAULT_PAY);
}
return strategy.get(paykey);
}
}
上层模块:订单
package com.jdwa.strategy;
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 MsgResult pay(){
return pay(PayStrategy.DEFAULT_PAY);
}
public MsgResult pay(String paykey){
Payment payment = PayStrategy.get(paykey);
System.out.println("欢迎使用"+payment.getName());
System.out.println("本次交易金额为"+amount+",开始扣款");
return payment.pay(uid,amount);
}
}
测试:
package com.jdwa.strategy;
public class Client {
public static void main(String[] args) {
Order order = new Order("1","4532787832456845434",800);
System.out.println(order.pay());
System.out.println("=============分割线================");
System.out.println(order.pay(PayStrategy.WECHAT_PAY));
}
}
结果:
欢迎使用支付宝
本次交易金额为800.0,开始扣款
MsgResult{code=200, data=支付成功, msg='支付金额800.0'}
=============分割线================
欢迎使用微信
本次交易金额为800.0,开始扣款
MsgResult{code=500, data=支付失败, msg='余额不足'}