定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。
策略抽象
/**
* @Author: chuan.bai
* @Description 策略抽象
* @Date: Created on 17:25 2021/3/24
* @Modified By:
*/
public interface PayStrategy {
void doPay(PayOrderRequest request);
}
提交支付单策略
/**
* @Author: chuan.bai
* @Description 提交支付单的策略
* @Date: Created on 17:46 2021/3/24
* @Modified By:
*/
public class SubmitOrderStrategy implements PayStrategy{
@Override
public void doPay(PayOrderRequest request) {
System.out.println("执行提交支付单操作");
}
}
查询支付单的策略
/**
* @Author: chuan.bai
* @Description 查询支付单的策略
* @Date: Created on 17:46 2021/3/24
* @Modified By:
*/
public class QueryPayStrategy implements PayStrategy {
@Override
public void doPay(PayOrderRequest request) {
System.out.println("执行查询支付单操作");
}
}
取消支付的策略
/**
* @Author: chuan.bai
* @Description 取消支付的策略
* @Date: Created on 17:53 2021/3/24
* @Modified By:
*/
public class CancelOrderStrategy implements PayStrategy{
@Override
public void doPay(PayOrderRequest request) {
System.out.println("执行取消支付单操作");
}
}
支付策略上下文
/**
* @Author: chuan.bai
* @Description 支付策略上下文
* @Date: Created on 17:50 2021/3/24
* @Modified By:
*/
public class PayContext {
private PayStrategy payStrategy;
public PayContext(PayStrategy payStrategy) {
this.payStrategy = payStrategy;
}
public void executePay(PayOrderRequest request){
payStrategy.doPay(request);
}
}
顾客操作类
/**
* @Author: chuan.bai
* @Description 顾客
* @Date: Created on 17:56 2021/3/24
* @Modified By:
*/
public class Customer {
public static void main(String[] args) {
//取消支付单
PayOrderRequest payOrderRequest = new PayOrderRequest();
PayContext payContext = new PayContext(new SubmitOrderStrategy());
payContext.executePay(payOrderRequest);
//取消支付单
payContext = new PayContext(new CancelOrderStrategy());
payContext.executePay(payOrderRequest);
}
}
网友评论