Java 外卖点餐系统订单管理类:封装、集合、计算和状态管理
import java.util.*;
public class Order {
private int id; // 订单编号
private String customerName; // 订餐人姓名
private LinkedList<Dish> dishes; // 菜品列表
private double totalPrice; // 合计价格
private Date orderTime; // 下单时间
private Date receiveTime; // 确认收货时间
private int state;// 0未出单 1已出单未收货 2已收货
public Order(int id, String customerName, LinkedList<Dish> dishes) {
this.id = id;
this.customerName = customerName;
this.dishes = dishes;
this.totalPrice = calculateTotalPrice();
this.orderTime = new Date();
this.receiveTime = null;
this.state = 0;
}
// 计算合计价格
private double calculateTotalPrice() {
double totalPrice = 0;
for (Dish dish : this.dishes) {
totalPrice += dish.getPrice() * dish.getQuantity();
}
return totalPrice;
}
// 确认收货
public void confirmReceive() {
this.receiveTime = new Date();
}
// 获取订单编号
public int getId() {
return this.id;
}
// 获取订餐人姓名
public String getCustomerName() {
return this.customerName;
}
// 获取菜品列表
public LinkedList<Dish> getDishes() {
return this.dishes;
}
// 获取合计价格
public double getTotalPrice() {
return this.totalPrice;
}
// 获取下单时间
public Date getOrderTime() {
return this.orderTime;
}
// 获取确认收货时间
public Date getReceiveTime() {
return this.receiveTime;
}
// 获取状态
public int getState() {
return this.state;
}
// 设置状态
public void setState(int state) {
this.state=state;
}
// string
public String toString() {
String string = '{订单编号:' + id +
',订餐人姓名:' + customerName +
',菜品列表:' + dishes +
',合计价格:' + totalPrice +
',下单时间:' + orderTime +
',确认收货时间:' + receiveTime +
',订单状态:' + state
+ '}';
return string;
}
}
这段代码用到了什么基本原理或技术内容:
1. 封装:将订单的属性私有化,并提供公共方法来访问和修改属性。
2. 集合:使用LinkedList作为菜品列表,方便添加、删除和遍历菜品。
3. 计算:使用calculateTotalPrice方法来计算订单的合计价格。
4. 时间:使用Java内置的Date类来处理订单的下单时间和确认收货时间。
5. 枚举:使用state属性来表示订单的状态,0为未出单,1为已出单未收货,2为已收货,相当于一个简单的状态机。
6. 重载toString方法:方便输出订单的信息。
原文地址: https://www.cveoy.top/t/topic/oWaO 著作权归作者所有。请勿转载和采集!