本文目录导读:

在Java中匹配状态信息有多种方式,具体取决于你的业务场景和状态管理的复杂程度,以下是几种常见且实用的方案:
使用枚举类型(最推荐)
public enum OrderStatus {
PENDING(0, "待处理"),
PROCESSING(1, "处理中"),
COMPLETED(2, "已完成"),
CANCELLED(3, "已取消");
private final int code;
private final String description;
OrderStatus(int code, String description) {
this.code = code;
this.description = description;
}
// 通过code匹配状态
public static OrderStatus fromCode(int code) {
for (OrderStatus status : values()) {
if (status.code == code) {
return status;
}
}
throw new IllegalArgumentException("无效的状态码: " + code);
}
// 获取状态描述
public String getDescription() {
return description;
}
}
// 使用示例
public class OrderService {
public void processOrder(Integer statusCode) {
OrderStatus status = OrderStatus.fromCode(statusCode);
switch (status) {
case PENDING:
System.out.println("订单等待处理");
break;
case PROCESSING:
System.out.println("订单正在处理");
break;
case COMPLETED:
System.out.println("订单已完成");
break;
case CANCELLED:
System.out.println("订单已取消");
break;
}
}
}
使用策略模式(复杂业务逻辑)
// 状态处理接口
public interface StatusHandler {
void handle();
}
// 具体状态处理器
@Component
public class PendingHandler implements StatusHandler {
@Override
public void handle() {
System.out.println("处理待处理状态...");
// 具体业务逻辑
}
}
@Component
public class CompletedHandler implements StatusHandler {
@Override
public void handle() {
System.out.println("处理已完成状态...");
// 具体业务逻辑
}
}
// 状态匹配器
@Component
public class StatusMatcher {
private final Map<Integer, StatusHandler> handlerMap;
@Autowired
public StatusMatcher(List<StatusHandler> handlers) {
handlerMap = new HashMap<>();
// 假设状态码映射
handlerMap.put(0, handlers.get(0)); // PENDING
handlerMap.put(2, handlers.get(1)); // COMPLETED
}
public void matchAndHandle(int statusCode) {
StatusHandler handler = handlerMap.get(statusCode);
if (handler == null) {
throw new IllegalArgumentException("未找到状态处理器: " + statusCode);
}
handler.handle();
}
}
使用Map缓存(简单场景)
public class OrderStatusMatcher {
private static final Map<Integer, String> STATUS_MAP = new HashMap<>();
static {
STATUS_MAP.put(0, "待处理");
STATUS_MAP.put(1, "处理中");
STATUS_MAP.put(2, "已完成");
STATUS_MAP.put(3, "已取消");
}
// 方法1: 直接获取描述
public static String getStatusDescription(int statusCode) {
return STATUS_MAP.getOrDefault(statusCode, "未知状态");
}
// 方法2: 判断状态是否有效
public static boolean isValidStatus(int statusCode) {
return STATUS_MAP.containsKey(statusCode);
}
// 方法3: 批处理状态
public static List<String> getStatusDescriptions(List<Integer> statusCodes) {
return statusCodes.stream()
.map(code -> STATUS_MAP.getOrDefault(code, "未知状态"))
.collect(Collectors.toList());
}
}
// 使用示例
public class OrderController {
public void updateOrderStatus(Integer statusCode) {
if (!OrderStatusMatcher.isValidStatus(statusCode)) {
throw new BusinessException("无效的状态");
}
String description = OrderStatusMatcher.getStatusDescription(statusCode);
System.out.println("更新订单状态为: " + description);
}
}
使用函数式接口(Java 8+)
public class FunctionalStatusMatcher {
private static final Map<Integer, Consumer<Order>> STATUS_ACTIONS = new HashMap<>();
static {
STATUS_ACTIONS.put(0, order -> {
System.out.println("验证订单...");
order.validate();
});
STATUS_ACTIONS.put(1, order -> {
System.out.println("处理支付...");
order.processPayment();
});
STATUS_ACTIONS.put(2, order -> {
System.out.println("发送通知...");
order.sendNotification();
});
}
public static void executeAction(int statusCode, Order order) {
STATUS_ACTIONS.getOrDefault(statusCode, order1 -> {
throw new RuntimeException("未知状态: " + statusCode);
}).accept(order);
}
}
状态机(复杂状态流转)
public enum OrderStateMachine {
PENDING {
@Override
public OrderStateMachine next(int action) {
switch (action) {
case 1: return PROCESSING;
case 2: return CANCELLED;
default: throw new IllegalStateException("无效操作");
}
}
},
PROCESSING {
@Override
public OrderStateMachine next(int action) {
switch (action) {
case 3: return COMPLETED;
case 2: return CANCELLED;
default: throw new IllegalStateException("无效操作");
}
}
},
COMPLETED, CANCELLED; // 终态
public OrderStateMachine next(int action) {
throw new IllegalStateException("终态不允许转换");
}
}
选择建议
| 场景 | 推荐方式 | 理由 |
|---|---|---|
| 简单状态码映射 | 枚举 + Map | 简洁、类型安全 |
| 状态需要描述信息 | 枚举 | 自带描述、易于扩展 |
| 不同状态有不同业务逻辑 | 策略模式 | 解耦、易于维护 |
| 状态流转复杂 | 状态机 | 清晰定义状态转换规则 |
| 需要动态扩展状态 | Map + 函数式接口 | 灵活、运行时修改 |
最佳实践
// 综合应用示例
public class StatusService {
// 1. 枚举定义状态
public enum Status {
DRAFT("草稿"),
PENDING("待审批"),
APPROVED("已通过"),
REJECTED("已拒绝");
private String label;
Status(String label) { this.label = label; }
}
// 2. 策略模式处理
private final Map<Status, BiConsumer<Order, User>> handlers = new EnumMap<>(Status.class);
@PostConstruct
public void init() {
handlers.put(Status.DRAFT, (order, user) -> System.out.println("草稿状态处理"));
handlers.put(Status.PENDING, (order, user) -> System.out.println("待审批处理"));
handlers.put(Status.APPROVED, (order, user) -> System.out.println("已通过处理"));
handlers.put(Status.REJECTED, (order, user) -> System.out.println("已拒绝处理"));
}
// 3. 统一入口
public void processStatus(Status status, Order order, User user) {
handlers.getOrDefault(status, (o, u) -> {
throw new BusinessException("未处理的状态: " + status);
}).accept(order, user);
}
}
根据你的具体需求选择合适的方案,通常枚举 + 策略模式的组合能够应对大多数业务场景。