23种设计模式——(2) 策略模式

23种设计模式——(2) 策略模式

1. 介绍

策略模式(Strategy):他定义了算法家族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。

策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,他可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合。

简要描述:
猫和狗都继承自Animal,都会叫:猫–喵喵;狗–汪汪;
在这里插入图片描述

1、 接口PayStrategy:

public interface PayStrategy {
    // 付款
    void unifiedOrder(Integer orderId, BigDecimal price);
    // 退款
    boolean refund(Integer orderId);
}

2、具体实现1-WeChatPayStrategy

public class WeChatPayStrategy implements PayStrategy{
    @Override
    public void unifiedOrder(Integer orderId, BigDecimal price) {
        System.out.println("微信下单支付");
    }

    @Override
    public boolean refund(Integer orderId) {
        System.out.println("微信退款成功");
        return true;
    }
}

3、具体实现2-ApplePayStrategy

public class ApplePayStrategy implements PayStrategy{
    @Override
    public void unifiedOrder(Integer orderId, BigDecimal price) {
        System.out.println("苹果下单支付");
    }

    @Override
    public boolean refund(Integer orderId) {
        System.out.println("苹果退款成功");
        return true;
    }
}

4、 Context :是上下文,用一个ConcreteStrategy来配置,维护一个对Strategy对象的引用

public class PayContext {
    PayStrategy payStrategy;

    public PayContext(PayStrategy payStrategy) {
        this.payStrategy = payStrategy;
    }

    public void getPay(){
        payStrategy.unifiedOrder(new Random(10).nextInt(),new BigDecimal("1"));
    }

    public void getRefund(){
        payStrategy.refund(new Random(10).nextInt());
    }
}

5、 单元测试

public class Client {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("请输入支付方式(1微信/22苹果支付):");
        int in = scanner.nextInt();
        PayContext payContext = null;
        switch (in){
            case 1:
                payContext = new PayContext(new WeChatPayStrategy());
                break;
            case 2:
                payContext = new PayContext(new ApplePayStrategy());
                break;
        }
        payContext.getPay();
        payContext.getRefund();
    }
}

遗留问题
(1) 和简单工厂模式的区别是什么????
https://www.cnblogs.com/cxydczzl/p/9583060.html

参考链接:
(1) 程序实现参考链接
https://blog.csdn.net/qq_41977838/article/details/114126943
(2) 图片参考链接:
https://blog.csdn.net/qq_36821220/article/details/108395001

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值