java实现设计模式--策略模式

2022-02-22  本文已影响0人  生不悔改

什么是策略模式?

我们平时遇到支付的时候,我们会考虑是用 支付宝微信 ,还是云闪付去完成 支付 这个动作。如果你选择微信,那你就用微信去完成支付。这个场景其实就是一种策略选择。
策略模式其实就是不同的主体都可以完成同一行为(行为过程不一样,结果一样)。
换成编程的思想上来说,就是在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。

策略模式简单代码实现

定义PayService接口

/**
 * @author: 
 * @date: 2022/2/22 10:56
 * @description: 支付接口
 */
public interface PayService {

    /**
     * 定义抽象支付动作
     */
    void pay(int count);
}

支付宝类Alipay,实现PayService

/**
 * @author: 
 * @date: 2022/2/22 10:58
 * @description: 支付宝支付
 */
public class Alipay implements PayService {
    @Override
    public void pay(int count) {
        System.out.println("支付宝支付:" + count + "元");
    }
}

云闪付类UnionPay,实现PayService

/**
 * @author: 
 * @date: 2022/2/22 10:58
 * @description: 云闪付支付
 */
public class UnionPay implements PayService {
    @Override
    public void pay(int count) {
        System.out.println("云闪付支付:" + count + "元");
    }
}

微信类WinXInPay,实现PayService

/**
 * @author: 
 * @date: 2022/2/22 10:58
 * @description: 微信支付
 */
public class WinXInPay implements PayService {
    @Override
    public void pay(int count) {
        System.out.println("微信支付:" + count + "元");
    }
}

统一策略选择器类 StrategyExecutor

/**
 * @author: 
 * @date: 2022/2/22 11:02
 * @description: 策略选择中转点
 */
public class StrategyExecutor {
    /**
     * 定义成员属性
     */
    private PayService payService;

    /**
     * 带参构造函数
     * @param payService
     */
    public StrategyExecutor(PayService payService) {
        this.payService = payService;
    }

    /**
     * 执行器执行的方法
     */
    public void execute(int count){
        payService.pay(count);
    }
}

测试类

/**
 * @author: 
 * @date: 2022/2/22 11:00
 * @description: 策略模式测试类
 */
public class Test {
    public static void main(String[] args) {
        // 在构造执行器的时候,传不一样的策略主体    -- 支付宝
        StrategyExecutor strategyExecutor = new StrategyExecutor(new Alipay());
        strategyExecutor.execute(10);
        
        // 在构造执行器的时候,传不一样的策略主体    -- 微信
        StrategyExecutor strategyExecutor1 = new StrategyExecutor(new WinXInPay());
        strategyExecutor1.execute(20);
        
        // 在构造执行器的时候,传不一样的策略主体    -- 云闪付
        StrategyExecutor strategyExecutor2 = new StrategyExecutor(new UnionPay());
        strategyExecutor2.execute(30);
    }
}

执行结果:

支付宝支付:10元
微信支付:20元
云闪付支付:30元

Process finished with exit code 0

以上就是简单的策略模式的实现。但是在实际开发,以及框架中,往往在使用策略模式的时候都是会有变形的,只是思想上没有变,这里还需要大家细细品味,理解其中的原理思想。

菜鸟教程对策略模式的介绍:

优点: 1、算法可以自由切换。 2、避免使用多重条件判断。 3、扩展性良好。
缺点: 1、策略类会增多。 2、所有策略类都需要对外暴露。

使用场景: 1、如果在一个系统里面有许多类,它们之间的区别仅在于它们的行为,那么使用策略模式可以动态地让一个对象在许多行为中选择一种行为。 2、一个系统需要动态地在几种算法中选择一种。 3、如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现。

注意事项:如果一个系统的策略多于四个,就需要考虑使用混合模式,解决策略类膨胀的问题。

上一篇 下一篇

猜你喜欢

热点阅读