03 - 流程引擎实现 ⚙️

1,030 阅读9分钟

🎯 目标: 实现流程编排框架的核心执行引擎

🤔 流程引擎的职责

流程引擎是整个框架的心脏,负责:

  • 🎯 流程调度: 按照定义的顺序执行步骤
  • 🔧 执行器管理: 为不同类型的步骤选择合适的执行器
  • 📊 状态跟踪: 记录流程和步骤的执行状态
  • 🛡️ 异常处理: 处理执行过程中的异常情况
  • 📈 性能监控: 收集执行时间和性能指标

🏗️ 引擎架构设计

graph TB
    subgraph "FlowEngine 🎯"
        A1[流程调度器]
        A2[执行器管理器]
        A3[状态管理器]
        A4[事件发布器]
    end
    
    subgraph "StepExecutor 🔧"
        B1[SimpleStepExecutor]
        B2[ServiceStepExecutor]
        B3[ConditionalStepExecutor]
        B4[ParallelStepExecutor]
    end
    
    subgraph "Context 📦"
        C1[FlowContext]
        C2[ExecutionContext]
        C3[StepContext]
    end
    
    A1 --> A2
    A1 --> A3
    A1 --> A4
    
    A2 --> B1
    A2 --> B2
    A2 --> B3
    A2 --> B4
    
    A1 --> C1
    B1 --> C2
    B2 --> C3

🎯 FlowEngine接口设计

/**
 * 流程引擎接口
 * 负责执行流程定义,管理执行状态和上下文
 */
public interface FlowEngine {
    
    /**
     * 执行流程
     * @param flowDefinition 流程定义
     * @param context 执行上下文
     * @return 执行结果
     */
    FlowExecutionResult execute(FlowDefinition flowDefinition, FlowContext context);
    
    /**
     * 异步执行流程
     * @param flowDefinition 流程定义
     * @param context 执行上下文
     * @return 异步执行结果
     */
    CompletableFuture<FlowExecutionResult> executeAsync(FlowDefinition flowDefinition, FlowContext context);
    
    /**
     * 注册步骤执行器
     * @param stepType 步骤类型
     * @param executor 执行器实例
     */
    void registerExecutor(StepType stepType, StepExecutor executor);
    
    /**
     * 获取步骤执行器
     * @param stepType 步骤类型
     * @return 执行器实例
     */
    StepExecutor getExecutor(StepType stepType);
    
    /**
     * 添加执行监听器
     * @param listener 监听器
     */
    void addListener(FlowExecutionListener listener);
    
    /**
     * 移除执行监听器
     * @param listener 监听器
     */
    void removeListener(FlowExecutionListener listener);
}

🔧 StepExecutor接口设计

/**
 * 步骤执行器接口
 * 负责执行特定类型的步骤
 */
public interface StepExecutor {
    
    /**
     * 执行步骤
     * @param stepDefinition 步骤定义
     * @param context 执行上下文
     * @return 执行结果
     */
    StepExecutionResult execute(StepDefinition stepDefinition, FlowContext context);
    
    /**
     * 获取支持的步骤类型
     * @return 步骤类型
     */
    StepType getSupportedType();
    
    /**
     * 验证步骤配置
     * @param stepDefinition 步骤定义
     * @return 验证结果
     */
    default ValidationResult validate(StepDefinition stepDefinition) {
        return ValidationResult.success();
    }
}

⚙️ DefaultFlowEngine实现

/**
 * 默认流程引擎实现
 * 提供基础的流程执行能力
 */
public class DefaultFlowEngine implements FlowEngine {
    
    private static final Logger logger = LoggerFactory.getLogger(DefaultFlowEngine.class);
    
    // 执行器注册表
    private final Map<StepType, StepExecutor> executors = new ConcurrentHashMap<>();
    
    // 执行监听器列表
    private final List<FlowExecutionListener> listeners = new CopyOnWriteArrayList<>();
    
    // 线程池(用于异步执行)
    private final ExecutorService executorService;
    
    public DefaultFlowEngine() {
        this.executorService = Executors.newCachedThreadPool(
            new ThreadFactoryBuilder()
                .setNameFormat("flow-engine-%d")
                .setDaemon(true)
                .build()
        );
        
        // 注册默认执行器
        registerDefaultExecutors();
    }
    
    @Override
    public FlowExecutionResult execute(FlowDefinition flowDefinition, FlowContext context) {
        logger.info("开始执行流程: {} [{}]", flowDefinition.getName(), flowDefinition.getId());
        
        long startTime = System.currentTimeMillis();
        FlowExecutionResult.Status status = FlowExecutionResult.Status.SUCCESS;
        List<StepExecutionResult> stepResults = new ArrayList<>();
        Throwable exception = null;
        
        try {
            // 发布流程开始事件
            publishEvent(new FlowStartedEvent(flowDefinition, context));
            
            // 验证流程定义
            validateFlowDefinition(flowDefinition);
            
            // 执行步骤
            for (StepDefinition stepDefinition : flowDefinition.getSteps()) {
                StepExecutionResult stepResult = executeStep(stepDefinition, context);
                stepResults.add(stepResult);
                
                // 如果步骤失败,根据配置决定是否继续
                if (stepResult.getStatus() == FlowExecutionResult.Status.FAILED) {
                    if (!shouldContinueOnFailure(stepDefinition)) {
                        status = FlowExecutionResult.Status.FAILED;
                        break;
                    }
                }
            }
            
        } catch (Exception e) {
            logger.error("流程执行异常: {} [{}]", flowDefinition.getName(), flowDefinition.getId(), e);
            status = FlowExecutionResult.Status.FAILED;
            exception = e;
        } finally {
            long endTime = System.currentTimeMillis();
            
            // 创建执行结果
            FlowExecutionResult result = new FlowExecutionResult(
                flowDefinition.getId(),
                status,
                context,
                stepResults,
                startTime,
                endTime,
                exception
            );
            
            // 发布流程完成事件
            publishEvent(new FlowCompletedEvent(flowDefinition, context, result));
            
            logger.info("流程执行完成: {} [{}], 状态: {}, 耗时: {}ms", 
                flowDefinition.getName(), 
                flowDefinition.getId(), 
                status, 
                endTime - startTime
            );
            
            return result;
        }
    }
    
    @Override
    public CompletableFuture<FlowExecutionResult> executeAsync(FlowDefinition flowDefinition, FlowContext context) {
        return CompletableFuture.supplyAsync(
            () -> execute(flowDefinition, context),
            executorService
        );
    }
    
    /**
     * 执行单个步骤
     */
    private StepExecutionResult executeStep(StepDefinition stepDefinition, FlowContext context) {
        logger.debug("开始执行步骤: {} [{}]", stepDefinition.getName(), stepDefinition.getId());
        
        long startTime = System.currentTimeMillis();
        FlowExecutionResult.Status status = FlowExecutionResult.Status.SUCCESS;
        Object result = null;
        Throwable exception = null;
        
        try {
            // 发布步骤开始事件
            publishEvent(new StepStartedEvent(stepDefinition, context));
            
            // 检查前置条件
            if (!checkPrecondition(stepDefinition, context)) {
                logger.info("步骤前置条件不满足,跳过执行: {} [{}]", 
                    stepDefinition.getName(), stepDefinition.getId());
                status = FlowExecutionResult.Status.SKIPPED;
                return createStepResult(stepDefinition, status, null, startTime, System.currentTimeMillis(), null);
            }
            
            // 获取执行器
            StepExecutor executor = getExecutor(stepDefinition.getType());
            if (executor == null) {
                throw new IllegalStateException("未找到步骤类型的执行器: " + stepDefinition.getType());
            }
            
            // 执行步骤
            StepExecutionResult stepResult = executor.execute(stepDefinition, context);
            status = stepResult.getStatus();
            result = stepResult.getResult();
            
        } catch (Exception e) {
            logger.error("步骤执行异常: {} [{}]", stepDefinition.getName(), stepDefinition.getId(), e);
            status = FlowExecutionResult.Status.FAILED;
            exception = e;
        } finally {
            long endTime = System.currentTimeMillis();
            
            // 创建步骤执行结果
            StepExecutionResult stepResult = createStepResult(
                stepDefinition, status, result, startTime, endTime, exception
            );
            
            // 发布步骤完成事件
            publishEvent(new StepCompletedEvent(stepDefinition, context, stepResult));
            
            logger.debug("步骤执行完成: {} [{}], 状态: {}, 耗时: {}ms", 
                stepDefinition.getName(), 
                stepDefinition.getId(), 
                status, 
                endTime - startTime
            );
            
            return stepResult;
        }
    }
    
    /**
     * 检查前置条件
     */
    private boolean checkPrecondition(StepDefinition stepDefinition, FlowContext context) {
        String precondition = stepDefinition.getPrecondition();
        if (precondition == null || precondition.trim().isEmpty()) {
            return true;
        }
        
        try {
            // 使用表达式引擎评估条件(简化实现)
            return evaluateExpression(precondition, context);
        } catch (Exception e) {
            logger.warn("前置条件评估失败: {}, 默认为true", precondition, e);
            return true;
        }
    }
    
    /**
     * 评估表达式(简化实现)
     */
    private boolean evaluateExpression(String expression, FlowContext context) {
        // 这里是简化实现,实际项目中应该使用专门的表达式引擎
        // 如SpEL、OGNL等
        if ("true".equals(expression)) {
            return true;
        }
        if ("false".equals(expression)) {
            return false;
        }
        
        // 简单的上下文变量检查
        if (expression.startsWith("context.containsKey(")) {
            String key = expression.substring(20, expression.length() - 2);
            key = key.replace("'", "").replace(""", "");
            return context.containsKey(key);
        }
        
        return true;
    }
    
    /**
     * 判断是否在失败时继续执行
     */
    private boolean shouldContinueOnFailure(StepDefinition stepDefinition) {
        Object continueOnFailure = stepDefinition.getConfig().get("continueOnFailure");
        return Boolean.TRUE.equals(continueOnFailure);
    }
    
    /**
     * 创建步骤执行结果
     */
    private StepExecutionResult createStepResult(
            StepDefinition stepDefinition,
            FlowExecutionResult.Status status,
            Object result,
            long startTime,
            long endTime,
            Throwable exception) {
        
        return new StepExecutionResult(
            stepDefinition.getId(),
            stepDefinition.getType(),
            status,
            result,
            startTime,
            endTime,
            exception
        );
    }
    
    /**
     * 验证流程定义
     */
    private void validateFlowDefinition(FlowDefinition flowDefinition) {
        if (flowDefinition == null) {
            throw new IllegalArgumentException("流程定义不能为空");
        }
        
        if (flowDefinition.getSteps() == null || flowDefinition.getSteps().isEmpty()) {
            throw new IllegalArgumentException("流程必须包含至少一个步骤");
        }
        
        // 验证步骤ID唯一性
        Set<String> stepIds = new HashSet<>();
        for (StepDefinition step : flowDefinition.getSteps()) {
            if (!stepIds.add(step.getId())) {
                throw new IllegalArgumentException("步骤ID重复: " + step.getId());
            }
        }
        
        // 验证步骤配置
        for (StepDefinition step : flowDefinition.getSteps()) {
            StepExecutor executor = getExecutor(step.getType());
            if (executor != null) {
                ValidationResult validationResult = executor.validate(step);
                if (!validationResult.isValid()) {
                    throw new IllegalArgumentException(
                        String.format("步骤配置无效 [%s]: %s", 
                            step.getId(), validationResult.getErrorMessage())
                    );
                }
            }
        }
    }
    
    /**
     * 发布事件
     */
    private void publishEvent(FlowExecutionEvent event) {
        for (FlowExecutionListener listener : listeners) {
            try {
                listener.onEvent(event);
            } catch (Exception e) {
                logger.warn("事件监听器执行异常", e);
            }
        }
    }
    
    /**
     * 注册默认执行器
     */
    private void registerDefaultExecutors() {
        registerExecutor(StepType.SIMPLE, new SimpleStepExecutor());
        registerExecutor(StepType.SERVICE, new ServiceStepExecutor());
        registerExecutor(StepType.CONDITIONAL, new ConditionalStepExecutor());
        // 其他执行器将在后续章节实现
    }
    
    @Override
    public void registerExecutor(StepType stepType, StepExecutor executor) {
        executors.put(stepType, executor);
        logger.info("注册步骤执行器: {} -> {}", stepType, executor.getClass().getSimpleName());
    }
    
    @Override
    public StepExecutor getExecutor(StepType stepType) {
        return executors.get(stepType);
    }
    
    @Override
    public void addListener(FlowExecutionListener listener) {
        listeners.add(listener);
    }
    
    @Override
    public void removeListener(FlowExecutionListener listener) {
        listeners.remove(listener);
    }
    
    /**
     * 关闭引擎,释放资源
     */
    public void shutdown() {
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(30, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}

🔧 基础执行器实现

🎯 SimpleStepExecutor

/**
 * 简单步骤执行器
 * 用于执行基础的同步操作
 */
public class SimpleStepExecutor implements StepExecutor {
    
    private static final Logger logger = LoggerFactory.getLogger(SimpleStepExecutor.class);
    
    @Override
    public StepExecutionResult execute(StepDefinition stepDefinition, FlowContext context) {
        logger.debug("执行简单步骤: {}", stepDefinition.getId());
        
        long startTime = System.currentTimeMillis();
        
        try {
            // 获取配置
            String action = (String) stepDefinition.getConfig().get("action");
            Object value = stepDefinition.getConfig().get("value");
            String targetKey = (String) stepDefinition.getConfig().get("targetKey");
            
            // 执行操作
            Object result = executeAction(action, value, context);
            
            // 保存结果到上下文
            if (targetKey != null && result != null) {
                context.put(targetKey, result);
            }
            
            long endTime = System.currentTimeMillis();
            
            return new StepExecutionResult(
                stepDefinition.getId(),
                stepDefinition.getType(),
                FlowExecutionResult.Status.SUCCESS,
                result,
                startTime,
                endTime,
                null
            );
            
        } catch (Exception e) {
            logger.error("简单步骤执行失败: {}", stepDefinition.getId(), e);
            
            return new StepExecutionResult(
                stepDefinition.getId(),
                stepDefinition.getType(),
                FlowExecutionResult.Status.FAILED,
                null,
                startTime,
                System.currentTimeMillis(),
                e
            );
        }
    }
    
    /**
     * 执行具体操作
     */
    private Object executeAction(String action, Object value, FlowContext context) {
        if ("set".equals(action)) {
            return value;
        } else if ("get".equals(action)) {
            return context.get((String) value);
        } else if ("increment".equals(action)) {
            String key = (String) value;
            Integer current = context.get(key, 0);
            return current + 1;
        } else if ("sleep".equals(action)) {
            try {
                Thread.sleep(((Number) value).longValue());
                return "slept for " + value + "ms";
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("Sleep interrupted", e);
            }
        }
        
        return "action executed: " + action;
    }
    
    @Override
    public StepType getSupportedType() {
        return StepType.SIMPLE;
    }
    
    @Override
    public ValidationResult validate(StepDefinition stepDefinition) {
        // 验证必要的配置
        String action = (String) stepDefinition.getConfig().get("action");
        if (action == null || action.trim().isEmpty()) {
            return ValidationResult.error("简单步骤必须指定action配置");
        }
        
        return ValidationResult.success();
    }
}

🌱 ServiceStepExecutor

/**
 * 服务步骤执行器
 * 用于调用Spring Bean的方法
 */
public class ServiceStepExecutor implements StepExecutor {
    
    private static final Logger logger = LoggerFactory.getLogger(ServiceStepExecutor.class);
    
    // Bean容器(简化实现,实际应该注入ApplicationContext)
    private final Map<String, Object> beanContainer = new ConcurrentHashMap<>();
    
    @Override
    public StepExecutionResult execute(StepDefinition stepDefinition, FlowContext context) {
        logger.debug("执行服务步骤: {}", stepDefinition.getId());
        
        long startTime = System.currentTimeMillis();
        
        try {
            // 获取配置
            String beanName = (String) stepDefinition.getConfig().get("beanName");
            String methodName = (String) stepDefinition.getConfig().get("methodName");
            Object[] args = getMethodArguments(stepDefinition, context);
            
            // 获取Bean实例
            Object bean = getBean(beanName);
            if (bean == null) {
                throw new IllegalStateException("未找到Bean: " + beanName);
            }
            
            // 调用方法
            Object result = invokeMethod(bean, methodName, args);
            
            // 保存结果到上下文
            String resultKey = (String) stepDefinition.getConfig().get("resultKey");
            if (resultKey != null && result != null) {
                context.put(resultKey, result);
            }
            
            long endTime = System.currentTimeMillis();
            
            return new StepExecutionResult(
                stepDefinition.getId(),
                stepDefinition.getType(),
                FlowExecutionResult.Status.SUCCESS,
                result,
                startTime,
                endTime,
                null
            );
            
        } catch (Exception e) {
            logger.error("服务步骤执行失败: {}", stepDefinition.getId(), e);
            
            return new StepExecutionResult(
                stepDefinition.getId(),
                stepDefinition.getType(),
                FlowExecutionResult.Status.FAILED,
                null,
                startTime,
                System.currentTimeMillis(),
                e
            );
        }
    }
    
    /**
     * 获取方法参数
     */
    private Object[] getMethodArguments(StepDefinition stepDefinition, FlowContext context) {
        @SuppressWarnings("unchecked")
        List<String> argKeys = (List<String>) stepDefinition.getConfig().get("arguments");
        
        if (argKeys == null || argKeys.isEmpty()) {
            return new Object[0];
        }
        
        Object[] args = new Object[argKeys.size()];
        for (int i = 0; i < argKeys.size(); i++) {
            args[i] = context.get(argKeys.get(i));
        }
        
        return args;
    }
    
    /**
     * 获取Bean实例
     */
    private Object getBean(String beanName) {
        return beanContainer.get(beanName);
    }
    
    /**
     * 调用方法
     */
    private Object invokeMethod(Object bean, String methodName, Object[] args) throws Exception {
        Class<?> beanClass = bean.getClass();
        
        // 查找匹配的方法
        Method method = findMethod(beanClass, methodName, args);
        if (method == null) {
            throw new NoSuchMethodException(
                String.format("未找到方法: %s.%s", beanClass.getSimpleName(), methodName)
            );
        }
        
        // 调用方法
        method.setAccessible(true);
        return method.invoke(bean, args);
    }
    
    /**
     * 查找匹配的方法
     */
    private Method findMethod(Class<?> clazz, String methodName, Object[] args) {
        Method[] methods = clazz.getMethods();
        
        for (Method method : methods) {
            if (method.getName().equals(methodName) && 
                method.getParameterCount() == args.length) {
                return method;
            }
        }
        
        return null;
    }
    
    /**
     * 注册Bean
     */
    public void registerBean(String name, Object bean) {
        beanContainer.put(name, bean);
        logger.info("注册Bean: {} -> {}", name, bean.getClass().getSimpleName());
    }
    
    @Override
    public StepType getSupportedType() {
        return StepType.SERVICE;
    }
    
    @Override
    public ValidationResult validate(StepDefinition stepDefinition) {
        String beanName = (String) stepDefinition.getConfig().get("beanName");
        String methodName = (String) stepDefinition.getConfig().get("methodName");
        
        if (beanName == null || beanName.trim().isEmpty()) {
            return ValidationResult.error("服务步骤必须指定beanName配置");
        }
        
        if (methodName == null || methodName.trim().isEmpty()) {
            return ValidationResult.error("服务步骤必须指定methodName配置");
        }
        
        return ValidationResult.success();
    }
}

📊 事件系统设计

🎯 FlowExecutionEvent

/**
 * 流程执行事件基类
 */
public abstract class FlowExecutionEvent {
    
    private final long timestamp;
    private final FlowDefinition flowDefinition;
    private final FlowContext context;
    
    protected FlowExecutionEvent(FlowDefinition flowDefinition, FlowContext context) {
        this.timestamp = System.currentTimeMillis();
        this.flowDefinition = flowDefinition;
        this.context = context;
    }
    
    // getter方法...
}

/**
 * 流程开始事件
 */
public class FlowStartedEvent extends FlowExecutionEvent {
    public FlowStartedEvent(FlowDefinition flowDefinition, FlowContext context) {
        super(flowDefinition, context);
    }
}

/**
 * 流程完成事件
 */
public class FlowCompletedEvent extends FlowExecutionEvent {
    
    private final FlowExecutionResult result;
    
    public FlowCompletedEvent(FlowDefinition flowDefinition, FlowContext context, FlowExecutionResult result) {
        super(flowDefinition, context);
        this.result = result;
    }
    
    public FlowExecutionResult getResult() {
        return result;
    }
}

/**
 * 步骤开始事件
 */
public class StepStartedEvent extends FlowExecutionEvent {
    
    private final StepDefinition stepDefinition;
    
    public StepStartedEvent(StepDefinition stepDefinition, FlowContext context) {
        super(null, context); // 简化实现
        this.stepDefinition = stepDefinition;
    }
    
    public StepDefinition getStepDefinition() {
        return stepDefinition;
    }
}

/**
 * 步骤完成事件
 */
public class StepCompletedEvent extends FlowExecutionEvent {
    
    private final StepDefinition stepDefinition;
    private final StepExecutionResult result;
    
    public StepCompletedEvent(StepDefinition stepDefinition, FlowContext context, StepExecutionResult result) {
        super(null, context); // 简化实现
        this.stepDefinition = stepDefinition;
        this.result = result;
    }
    
    // getter方法...
}

🎧 FlowExecutionListener

/**
 * 流程执行监听器接口
 */
public interface FlowExecutionListener {
    
    /**
     * 处理执行事件
     * @param event 执行事件
     */
    void onEvent(FlowExecutionEvent event);
    
    /**
     * 流程开始时调用
     * @param event 流程开始事件
     */
    default void onFlowStarted(FlowStartedEvent event) {
        // 默认空实现
    }
    
    /**
     * 流程完成时调用
     * @param event 流程完成事件
     */
    default void onFlowCompleted(FlowCompletedEvent event) {
        // 默认空实现
    }
    
    /**
     * 步骤开始时调用
     * @param event 步骤开始事件
     */
    default void onStepStarted(StepStartedEvent event) {
        // 默认空实现
    }
    
    /**
     * 步骤完成时调用
     * @param event 步骤完成事件
     */
    default void onStepCompleted(StepCompletedEvent event) {
        // 默认空实现
    }
}

🧪 使用示例

public class FlowEngineExample {
    
    public static void main(String[] args) {
        // 创建流程引擎
        DefaultFlowEngine engine = new DefaultFlowEngine();
        
        // 注册测试Bean
        ServiceStepExecutor serviceExecutor = (ServiceStepExecutor) engine.getExecutor(StepType.SERVICE);
        serviceExecutor.registerBean("testService", new TestService());
        
        // 添加监听器
        engine.addListener(new LoggingFlowExecutionListener());
        
        // 创建流程定义
        FlowDefinition flow = FlowDefinitionBuilder
            .builder("test-flow")
            .name("测试流程")
            .addStep(
                StepDefinitionBuilder
                    .builder("init", StepType.SIMPLE)
                    .config("action", "set")
                    .config("value", "Hello World")
                    .config("targetKey", "message")
                    .build()
            )
            .addStep(
                StepDefinitionBuilder
                    .serviceStep("process", "testService", "processMessage")
                    .config("arguments", Arrays.asList("message"))
                    .config("resultKey", "result")
                    .build()
            )
            .addStep(
                StepDefinitionBuilder
                    .builder("output", StepType.SIMPLE)
                    .config("action", "get")
                    .config("value", "result")
                    .build()
            )
            .build();
        
        // 创建执行上下文
        FlowContext context = new DefaultFlowContext();
        
        // 执行流程
        FlowExecutionResult result = engine.execute(flow, context);
        
        // 输出结果
        System.out.println("执行状态: " + result.getStatus());
        System.out.println("执行时间: " + (result.getEndTime() - result.getStartTime()) + "ms");
        System.out.println("上下文数据: " + context.getAll());
        
        // 关闭引擎
        engine.shutdown();
    }
    
    /**
     * 测试服务类
     */
    public static class TestService {
        public String processMessage(String message) {
            return "Processed: " + message;
        }
    }
    
    /**
     * 日志监听器
     */
    public static class LoggingFlowExecutionListener implements FlowExecutionListener {
        
        @Override
        public void onEvent(FlowExecutionEvent event) {
            if (event instanceof FlowStartedEvent) {
                onFlowStarted((FlowStartedEvent) event);
            } else if (event instanceof FlowCompletedEvent) {
                onFlowCompleted((FlowCompletedEvent) event);
            } else if (event instanceof StepStartedEvent) {
                onStepStarted((StepStartedEvent) event);
            } else if (event instanceof StepCompletedEvent) {
                onStepCompleted((StepCompletedEvent) event);
            }
        }
        
        @Override
        public void onFlowStarted(FlowStartedEvent event) {
            System.out.println("🚀 流程开始: " + event.getFlowDefinition().getName());
        }
        
        @Override
        public void onFlowCompleted(FlowCompletedEvent event) {
            System.out.println("✅ 流程完成: " + event.getResult().getStatus());
        }
        
        @Override
        public void onStepStarted(StepStartedEvent event) {
            System.out.println("  🔧 步骤开始: " + event.getStepDefinition().getName());
        }
        
        @Override
        public void onStepCompleted(StepCompletedEvent event) {
            System.out.println("  ✅ 步骤完成: " + event.getResult().getStatus());
        }
    }
}

🎯 设计亮点

✨ 1. 责任分离

  • 🎯 引擎专注调度: FlowEngine只负责流程调度和状态管理
  • 🔧 执行器专注执行: StepExecutor专注于具体步骤的执行逻辑
  • 📊 清晰的接口: 每个组件都有明确的职责边界

✨ 2. 可扩展架构

  • 🔌 插件化执行器: 可以轻松添加新的步骤类型
  • 🎧 事件驱动: 通过事件系统实现松耦合的扩展
  • ⚙️ 配置驱动: 通过配置而非代码控制行为

✨ 3. 健壮性设计

  • 🛡️ 异常处理: 完善的异常捕获和处理机制
  • 参数验证: 在执行前验证配置的有效性
  • 📊 状态跟踪: 详细记录每个步骤的执行状态

✨ 4. 性能考虑

  • 异步支持: 提供异步执行能力
  • 🧵 线程安全: 使用线程安全的数据结构
  • 📈 性能监控: 记录执行时间等性能指标

🎉 小结

在这一章中,我们完成了:

  • ⚙️ 实现了FlowEngine: 核心的流程执行引擎
  • 🔧 设计了StepExecutor: 可扩展的步骤执行器架构
  • 🎯 实现了基础执行器: SimpleStepExecutor和ServiceStepExecutor
  • 📊 设计了事件系统: 支持流程执行的监控和扩展
  • 🧪 提供了完整示例: 展示了引擎的使用方法

🚀 下一步

在下一章《步骤执行器设计》中,我们将:

  • 🔧 深入设计更多类型的执行器
  • 🔀 实现条件分支执行器
  • ⚡ 实现并行执行器
  • 🔄 实现循环执行器
  • 🧪 编写完整的执行器测试

💡 思考题:

  1. 如何设计才能支持步骤的超时控制?
  2. 如何实现流程的暂停和恢复功能?
  3. 如何设计才能支持分布式环境下的流程执行?