You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

115 lines
3.6 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

/**
* 订单验证器类,用于验证订单的有效性
*/
package com.orderprocessing;
import java.util.ArrayList;
import java.util.List;
public class OrderValidator {
private static final int MAX_ORDER_ITEMS = 50;
private static final double MIN_ORDER_AMOUNT = 0.01;
/**
* 验证订单是否有效
* @param order 需要验证的订单
* @return 如果订单有效返回true否则返回false
*/
public boolean isValid(Order order) {
if (order == null) {
return false;
}
// 验证订单ID
if (order.getOrderId() == null || order.getOrderId().trim().isEmpty()) {
return false;
}
// 验证客户名称
if (order.getCustomerName() == null || order.getCustomerName().trim().isEmpty()) {
return false;
}
// 验证订单项
List<OrderItem> items = order.getItems();
if (items == null || items.isEmpty()) {
return false;
}
// 验证订单项数量上限
if (items.size() > MAX_ORDER_ITEMS) {
return false;
}
// 验证总金额
if (order.getTotalAmount() < MIN_ORDER_AMOUNT) {
return false;
}
// 验证每个订单项
for (OrderItem item : items) {
if (item == null ||
item.getProductId() == null ||
item.getProductId().trim().isEmpty() ||
item.getQuantity() <= 0 ||
item.getPrice() < 0) {
return false;
}
}
return true;
}
/**
* 获取订单验证的详细错误信息
* @param order 需要验证的订单
* @return 错误信息列表,如果没有错误则返回空列表
*/
public List<String> getValidationErrors(Order order) {
List<String> errors = new ArrayList<>();
if (order == null) {
errors.add("订单对象不能为空");
return errors;
}
if (order.getOrderId() == null || order.getOrderId().trim().isEmpty()) {
errors.add("订单ID不能为空");
}
if (order.getCustomerName() == null || order.getCustomerName().trim().isEmpty()) {
errors.add("客户名称不能为空");
}
List<OrderItem> items = order.getItems();
if (items == null || items.isEmpty()) {
errors.add("订单至少需要包含一个订单项");
} else if (items.size() > MAX_ORDER_ITEMS) {
errors.add("订单不能包含超过" + MAX_ORDER_ITEMS + "个订单项");
}
if (order.getTotalAmount() < MIN_ORDER_AMOUNT) {
errors.add("订单总金额必须大于" + MIN_ORDER_AMOUNT);
}
// 验证每个订单项
for (int i = 0; i < items.size(); i++) {
OrderItem item = items.get(i);
if (item == null) {
errors.add("第" + (i + 1) + "个订单项不能为空");
} else {
if (item.getProductId() == null || item.getProductId().trim().isEmpty()) {
errors.add("第" + (i + 1) + "个订单项的产品ID不能为空");
}
if (item.getQuantity() <= 0) {
errors.add("第" + (i + 1) + "个订单项的数量必须大于0");
}
if (item.getPrice() < 0) {
errors.add("第" + (i + 1) + "个订单项的价格不能为负数");
}
}
}
return errors;
}
}