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.
BookStore/src/com/yj/bean/Cart.java

140 lines
4.0 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.yj.bean;
/**
* @author yj
* @create 2020-10-02 20:12
*/
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* 购物车对象
*/
public class Cart {
// 注释掉的代码表示之前可能考虑过直接存储总数和总价,但在此实现中,选择动态计算这些值
//private Integer totalCount;
//private BigDecimal totalPrice;
/**
* 获取购物车中所有商品的总数量
*/
public Integer getTotalCount() {
Integer totalCount = 0;
// 初始化总数量为0
for (Map.Entry<Integer,CartItem>entry : items.entrySet()) {
// 遍历购物车中的每一项
totalCount += entry.getValue().getCount();
// 累加每一项的数量
}
return totalCount;
// 返回总数量
}
/**
* 获取购物车中所有商品的总价格
*/
public BigDecimal getTotalPrice() {
BigDecimal totalPrice = new BigDecimal(0);
// 初始化总价格为0
for (Map.Entry<Integer,CartItem>entry : items.entrySet()) {
// 遍历购物车中的每一项
totalPrice = totalPrice.add(entry.getValue().getTotalPrice());
// 累加每一项的总价格
}
return totalPrice;
// 返回总价格
}
/**
* 获取购物车中的所有商品项
*/
public Map<Integer, CartItem> getItems() {
return items;
// 返回购物车中的商品项
}
/**
* 设置购物车中的所有商品项
*/
public void setItems(Map<Integer, CartItem> items) {
this.items = items;
// 设置购物车中的商品项
}
/**
* 商品项存储的Mapkey是商品编号value是商品信息使用LinkedHashMap保持插入顺序
*/
private Map<Integer,CartItem> items = new LinkedHashMap<Integer, CartItem>();
/**
* 重写toString方法用于打印购物车信息
*/
@Override
public String toString() {
return "Cart{" +
"totalCount=" + getTotalCount() +
// 总数量
", totalPrice=" + getTotalPrice() +
// 总价格
", items=" + items +
// 商品项
'}';
}
/**
* 添加商品项到购物车
* @param cartItem 要添加的商品项
*/
public void addItem(CartItem cartItem) {
// 先查看购物车中是否包含此商品
CartItem item = items.get(cartItem.getId());
if(item == null) {
// 之前没有添加过此商品,直接添加到购物车中
items.put(cartItem.getId(),cartItem);
} else {
// 购物车中已有此商品数量加1并更新总金额
item.setCount(item.getCount() + 1);
// 数量累计
item.setTotalPrice(item.getPrice().multiply(new BigDecimal(item.getCount())));
// 更新总金额
}
}
/**
* 从购物车中删除指定编号的商品项
* @param id 要删除的商品项的编号
*/
public void deleteItem(Integer id) {
items.remove(id);
// 从购物车中删除指定编号的商品项
}
/**
* 清空购物车中的所有商品项
*/
public void clear() {
items.clear();
// 清空购物车
}
/**
* 修改购物车中指定编号的商品项的数量
* @param id 商品项的编号
* @param count 新的数量
*/
public void updateCount(Integer id,Integer count) {
// 先查看购物车中是否包含此商品项
CartItem cartItem = items.get(id);
if(cartItem != null) {
// 购物车中已有此商品项,修改数量并更新总金额
cartItem.setCount(count);
// 修改数量
cartItem.setTotalPrice(cartItem.getPrice().multiply(new BigDecimal(cartItem.getCount())));
// 更新总金额
}
}
}