MST
星途 面试题库

面试题:Java策略模式实现算法动态切换时如何处理策略间的依赖关系

在使用Java策略模式实现算法动态切换时,有时不同策略之间可能存在依赖关系,例如某个策略需要在另一个策略执行完成后才能执行,或者依赖其执行结果。请阐述你会如何设计来处理这种策略间的依赖关系。
23.8万 热度难度
编程语言Java

知识考点

AI 面试

面试题答案

一键面试
  1. 定义策略接口
    • 首先定义所有策略需要实现的公共接口,例如:
    public interface Strategy {
        void execute();
    }
    
  2. 创建具体策略类
    • 每个具体策略类实现上述策略接口。
    • 对于有依赖关系的策略,在其构造函数中传入依赖的策略实例。
    public class DependentStrategy implements Strategy {
        private final Strategy dependentStrategy;
        public DependentStrategy(Strategy dependentStrategy) {
            this.dependentStrategy = dependentStrategy;
        }
        @Override
        public void execute() {
            dependentStrategy.execute();
            // 执行自身逻辑,这里可以依赖dependentStrategy的执行结果
            System.out.println("执行依赖策略后的自身逻辑");
        }
    }
    
  3. 策略上下文类
    • 创建策略上下文类,用于管理和执行策略。
    public class StrategyContext {
        private Strategy strategy;
        public StrategyContext(Strategy strategy) {
            this.strategy = strategy;
        }
        public void executeStrategy() {
            strategy.execute();
        }
    }
    
  4. 使用示例
    • 在客户端代码中,可以这样使用:
    public class Main {
        public static void main(String[] args) {
            Strategy baseStrategy = () -> System.out.println("基础策略执行");
            Strategy dependent = new DependentStrategy(baseStrategy);
            StrategyContext context = new StrategyContext(dependent);
            context.executeStrategy();
        }
    }
    

通过在有依赖关系的策略类构造函数中传入依赖策略实例,并在执行方法中先执行依赖策略,来处理策略间的依赖关系,实现算法的动态切换同时满足依赖需求。