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

在设计模式中除去工厂单例等, 策略模式 应该算最常用的设计模式之一

  • 在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。

  • 在策略模式中,我们创建表示各种策略的对象和一个行为随着策略对象改变而改变的 context 对象。策略对象改变 context 对象的执行算法。

介绍
  • 意图:定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。

  • 主要解决:在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。

  • 何时使用:一个系统有许多许多类,而区分它们的只是他们直接的行为。

  • 如何解决:将这些算法封装成一个一个的类,任意地替换。

  • 关键代码:实现同一个接口。

  • 优点:
    • 算法可以自由切换。
    • 避免使用多重条件判断。
    • 扩展性良好。
  • 缺点:
    • 策略类会增多,导致代码查看较为困难。
    • 所有策略类都需要对外暴露。
  • 使用场景:
    • 如果在一个系统里面有许多类,它们之间的区别仅在于它们的行为,那么使用策略模式可以动态地让一个对象在许多行为中选择一种行为。
    • 一个系统需要动态地在几种算法中选择一种。
    • 如果一个对象有很多的行为,如果不用恰当的模式,这些行为就只好使用多重的条件选择语句来实现。

示例

场景说明:
- 此处为导出功能,此时需要根据场景导出不同的数据
  1. 创建策略接口
public interface ExportStrategy {

    default void execute() {};

    default  void execute(Object o) {};
}
  1. 创建策略工厂
@Service
public class ExportContextFactory {

    @Autowired
    private Map<String, ExportStrategy> contextStrategy = new ConcurrentHashMap<>();

    public ExportStrategy get(String source) {
        ExportStrategy exportStrategy = this.contextStrategy.get(source);
        if (Objects.isNull(exportStrategy)) {
            throw new IllegalArgumentException();
        }
        return exportStrategy;
    }
}

3.多场景实现

@Component("demo1")
public class Demo1 implements ExportStrategy {
    @Override
    public void execute() {
        // do something 
    }
}
@Component("demo2")
public class Demo2 implements ExportStrategy {
    @Override
    public void execute(Object o) {
        // do something 
    }
}
  1. 调用
    @Autowired
    private ExportContextFactory exportContextFactory;
    @Test
    public void tjIntegral() {
        exportContextFactory.get("demo1").execute();
        Object o = new Object();
        
        exportContextFactory.get("demo2").execute(o);
    }

猜你喜欢

转载自www.cnblogs.com/heyouxin/p/12469010.html
今日推荐