策略模式(Strategy)

策略模式

该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。


结构

  • 抽象策略(strategy)类:这是一个抽象角色,通常由一个接口或抽象类实现。此角色给出所有的具体策略类所需的接口。
  • 具体策略((concrete strategy)类:实现了抽象策略定义的接口,提供具体的算法实现或行为。
  • 环境(context)类:持有一个策略类的引用,最终给客户端调用。

案例实现

  • 抽象策略接口
package strategy;

/**
 * @author pangjian
 * @Interface Strategy
 * @Description 抽象策略接口
 * @date 2021/10/18 17:57
 */

public interface Strategy {

    void strategy();

}
  • 具体策略类
package strategy;

/**
 * @author pangjian
 * @ClassName StrategyA
 * @Description 具体策略类
 * @date 2021/10/18 17:58
 */

public class StrategyA implements Strategy {

    @Override
    public void strategy() {
        System.out.println("双十一活动促销");
    }

}
package strategy;

/**
 * @author pangjian
 * @ClassName StrategyB
 * @Description 具体策略类
 * @date 2021/10/18 17:59
 */

public class StrategyB implements Strategy {

    @Override
    public void strategy() {
        System.out.println("618活动促销");
    }

}
  • 环境类(拿到具体策略,方便客户端调用)
package strategy;

import lombok.Setter;

/**
 * @author pangjian
 * @ClassName Executor
 * @Description 环境类
 * @date 2021/10/18 18:00
 */
@Setter
public class Executor {

    private Strategy strategy;

    public Executor(Strategy strategy) {
        this.strategy = strategy;
    }

    public void showStrategy() {
        strategy.strategy();
    }

}
  • 客户端
package strategy;

/**
 * @author pangjian
 * @ClassName Client
 * @Description TODO
 * @date 2021/10/18 18:09
 */

public class Client {

    public static void main(String[] args) {
        // 双十一
        Executor executor = new Executor(new StrategyA());
        executor.showStrategy();
        // 618
        executor.setStrategy(new StrategyB());
        executor.showStrategy();
    }

}

优缺点

优点:

  • 策略类之间可以自由切换,由于策略类都实现同一个接口,所以使它们之间可以自由切换。
  • 易于扩展,增加一个新的策略只需要添加一个具体的策略类即可,基本不需要改变原有的代码,符合"开闭原则"。
  • 避免使用多重条件选择语句(if else),充分体现面向对象设计思想。

缺点:

  • 客户端必须知道所有的策略类,并自行决定使用哪一个策略类。
  • 策略模式将造成产生很多策略类,可以通过使用享元模式在一定程度上减少对象的数量。

使用场景

  • 一个系统需要动态地在几种算法中选择一种时,可将每个算法封装到策略类中。
  • 一个类定义了多种行为,并且这些行为在这个类的操作中以多个条件语句的形式出现,可将每个条件分支移入它们各自的策略类中以代替这些条件语句。
  • 系统中各算法彼此完全独立,且要求对客户隐藏具体算法的实现细节时。
  • 系统要求使用算法的客户不应该知道其操作的数据时,可使用策略模式来隐藏与算法相关的数据结构。
  • 多个类只区别在表现行为不同,可以使用策略模式,在运行时动态选择具体要执行的行为。

实际应用

package cn.edu.guet.demo.strategy.pay;

/**
 * @author pangjian
 * @ClassName PayStrategy
 * @Description 抽象支付策略
 * @date 2021/10/18 21:01
 */

public interface PayStrategy {

    /**
     * @Description:支付共同方法行为
     * @return java.lang.String
     * @date 2021/10/18 21:12
    */
    String toPay ();
    
}
package cn.edu.guet.demo.strategy.pay.impl;

import cn.edu.guet.demo.strategy.pay.PayStrategy;
import org.springframework.stereotype.Component;

/**
 * @author pangjian
 * @ClassName AliPay
 * @Description 具体策略
 * @date 2021/10/18 21:02
 */
@Component
public class AliPay implements PayStrategy {

    @Override
    public String toPay() {
        return "支付宝支付";
    }

}
package cn.edu.guet.demo.strategy.pay;

import cn.edu.guet.demo.mapper.PayMapper;
import cn.edu.guet.demo.pojo.PaymentChannel;
import cn.edu.guet.demo.util.SpringBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * @author pangjian
 * @ClassName PayContextStrategy
 * @Description 环境类,获取具体策略实现
 * @date 2021/10/18 21:03
 */
@Component
public class PayContextStrategy {

    @Autowired
    private PayMapper payMapper;

    /**
     * @Description:获取具体策略
     * @return java.lang.String
     * @date 2021/10/18 21:31
    */
    public String toPay(String payCode) {
        if (StringUtils.isEmpty(payCode)) {
            return "payCode不能为空";
        }
        // 查询数据库获取具体策略实现
        PaymentChannel paymentChannel = payMapper.selectPayChannel(payCode);
        if (paymentChannel == null) {
            return "数据库没有配置该具体策略";
        }
        // 获取具体策略接口实例
        PayStrategy payStrategy = SpringBeanUtils.getBean(paymentChannel.getBeanId(), PayStrategy.class);
        return payStrategy.toPay();
    }

}
  • 工具类
package cn.edu.guet.demo.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author pangjian
 * @ClassName SpringBeanUtils
 * @Description 获取Spring IOC 容器中的bean对象
 * @date 2021/10/18 21:51
 */
@Component
public class SpringBeanUtils implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         this.applicationContext = applicationContext;
    }

    public static <T> T getBean(String name, Class<T> clazz) {
        return applicationContext.getBean(name, clazz);
    }

}
  • 通过数据库维护,也可以通过枚举

在这里插入图片描述

避免了支付类型的if判断。当新的支付类型加入,只需要编写该支付具体策略即可,在数据库加入该支付类型信息,就符合了开闭原则。不需要改源代码

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值