Java设计模式之二:策略模式

mac2022-06-30  9

引言

本文主要介绍策略模式的相关内容。主要说明策略模式是什么、怎么用及其对应的优缺点。

策略模式介绍代码示例总结

一、策略模式介绍

到底什么是策略模式呢?按照我自己的理解,简单来说就是将具备统一任务属性的一类业务逻辑进行封装,调用方可以根据自身的业务场景和需要,进行策略的业务调用。 通过上图可知,策略模式涉及到的模块主要包括以下三个方面: 1、策略环境:类中包含策略引用; 2、抽象策略:抽象策略公共行为,包含所有策略的接口方法; 3、策略具体实现:封装了策略的不同算法实现;

二、代码示例

1、策略场景

public class StrategyContext { //持有一个具体策略的对象 private Strategy strategy; /** * 构造函数,传入一个具体策略对象 * @param strategy 具体策略对象 */ public StrategyContext(Strategy strategy){ this.strategy = strategy; } /** * 策略方法 */ public void contextInterface(){ strategy.strategyInterface(); } }

2、策略接口

public interface Strategy { /** * 策略方法 */ public void strategyInterface(); }

3、策略实现

public class StrategyA implements Strategy { @Override public void strategyInterface() { //相关的业务 } } public class StrategyB implements Strategy { @Override public void strategyInterface() { //相关的业务 } }

4、策略使用

public class ContextClient { public static void main(String[] args) { Strategy StrategyA = new StrategyA(); StrategyContext contextA = new StrategyContext(StrategyA ); //调用策略A的执行方法 contextA.contextInterface(); } }

三、总结

策略模式的使用场景为把算法实现进行提取封装,独立于调用场景之外。

策略模式的优点: 1、当业务代码存在多重逻辑判断时,策略模式可以避免大量的if-else的判断,避免代码逻辑混乱,增强代码的可维护性; 2、可将策略中的公共部分进行高度抽象,避免代码重复;

策略模式的缺点: 1、调用方必须知道所有的策略实现类,增加了调用方的使用难度; 2、如果判断逻辑较多的话,会导致策略实现类较多;

最新回复(0)