状态机及策略模式的使用
状态机:
// 定义状态枚举 enum State { FLYING, LANDING, RETURNING, PAUSED } // 定义事件枚举 enum Event { BATTERY_LOW, GPS_LOST } // 状态机类 class DroneStateMachine { private State currentState; public DroneStateMachine() { // 初始状态 currentState = State.FLYING; } // 发送事件,处理状态转移 public void sendEvent(Event event) { switch (currentState) { case FLYING: if (event == Event.BATTERY_LOW) { System.out.println("Battery low, initiating return..."); currentState = State.RETURNING; // 电池低,返航 } else if (event == Event.GPS_LOST) { System.out.println("GPS lost, pausing..."); currentState = State.PAUSED; // GPS丢失,暂停 } break; case PAUSED: if (event == Event.BATTERY_LOW) { System.out.println("Battery low, initiating return..."); currentState = State.RETURNING; } break; case RETURNING: if (event == Event.GPS_LOST) { System.out.println("GPS lost, pausing..."); currentState = State.PAUSED; } break; default: break; } } // 获取当前状态 public State getCurrentState() { return currentState; } } public class Main { public static void main(String[] args) { DroneStateMachine droneStateMachine = new DroneStateMachine(); // 模拟触发事件 droneStateMachine.sendEvent(Event.BATTERY_LOW); // 电池低,触发返航 System.out.println("Current state: " + droneStateMachine.getCurrentState()); droneStateMachine.sendEvent(Event.GPS_LOST); // GPS丢失,触发暂停 System.out.println("Current state: " + droneStateMachine.getCurrentState()); } }
最后调用时,只需要关心无人机本身当前的状态即可,根据当前的状态做出对应事件触发。
策略模式:
1.定义飞行策略接口
public interface FlightStrategy { void execute(); }
2.实现具体策略类
// 电量低策略 public class LowBatteryStrategy implements FlightStrategy { @Override public void execute() { System.out.println("电量过低,执行紧急降落!"); // 控制硬件:sendCommand("LAND_IMMEDIATELY"); } } // GPS 丢失策略 public class GpsLostStrategy implements FlightStrategy { @Override public void execute() { System.out.println("GPS 丢失,悬停等待..."); // 控制硬件:sendCommand("HOVER"); } } // 信号丢失策略 public class SignalLostStrategy implements FlightStrategy { @Override public void execute() { System.out.println("信号丢失,执行自动返航!"); // 控制硬件:sendCommand("RETURN_HOME"); } }
3.定义策略上下文类(封装切换逻辑)
public class FlightContext { private FlightStrategy strategy; public void setStrategy(FlightStrategy strategy) { this.strategy = strategy; } public void handleFlightEvent() { if (strategy != null) { strategy.execute(); } } }
4.在主业务中使用策略
public void handleEvent(DroneEvent event) { switch (event) { case BATTERY_LOW: context.setStrategy(new LowBatteryStrategy()); break; case GPS_LOST: context.setStrategy(new GpsLostStrategy()); break; case SIGNAL_LOST: context.setStrategy(new SignalLostStrategy()); break; } context.handleFlightEvent(); }

浙公网安备 33010602011771号