package mxdx2; //订单流程编排器(状态模式) public class orchestration { private State currentState; private String orderId; private ServiceGateway gateway; public orchestration(ServiceGateway gateway) { this.gateway = gateway; this.currentState = new InitState(this); } // 启动订单流程 public void startProcess(String token, String userId, String productId) { currentState.process(token, userId, productId); } // 状态变更 public void setState(State state) { this.currentState = state; } // 获取网关 public ServiceGateway getGateway() { return gateway; } // 设置订单ID public void setOrderId(String orderId) { this.orderId = orderId; } // 状态接口 public interface State { void process(String token, String userId, String productId); } // 初始状态 public static class InitState implements State { private orchestration orchestrator; public InitState(orchestration orchestrator) { this.orchestrator = orchestrator; } @Override public void process(String token, String userId, String productId) { System.out.println("Starting order process..."); // 检查用户 String user = orchestrator.getGateway().getUser(token, userId); if (user == null) { throw new RuntimeException("User not found"); } // 检查商品 String product = orchestrator.getGateway().getProduct(token, productId); if (product == null) { throw new RuntimeException("Product not found"); } // 进入下一个状态 orchestrator.setState(new CreateOrderState(orchestrator)); orchestrator.currentState.process(token, userId, productId); } } // 创建订单状态 public static class CreateOrderState implements State { private orchestration orchestrator; public CreateOrderState(orchestration orchestrator) { this.orchestrator = orchestrator; } @Override public void process(String token, String userId, String productId) { System.out.println("Creating order..."); String orderId = orchestrator.getGateway().createOrder(token, userId, productId); orchestrator.setOrderId(orderId); // 进入完成状态 orchestrator.setState(new CompleteState(orchestrator)); orchestrator.currentState.process(token, userId, productId); } } // 完成状态 public static class CompleteState implements State { private orchestration orchestrator; public CompleteState(orchestration orchestrator) { this.orchestrator = orchestrator; } @Override public void process(String token, String userId, String productId) { System.out.println("Order process completed. Order ID: " + orchestrator.orderId); } } }