import java.util.HashMap;
import java.util.Iterator;
/*
* 购物车
*/
public class Cart {
/*
* 通过键值对保存OrderGoodsInfo对象的容器对象
*/
private HashMap<Integer, OrderGoodsInfo> cart;
/**
* 构造方法
*/
public Cart() {
cart = new HashMap<Integer,OrderGoodsInfo>();
}
/**
* 返回包含已经订购的商品信息的容器对象(即购物车对象)
* @return
*/
public HashMap<Integer,OrderGoodsInfo> getCart() {
return cart;
}
/**
* 添加一件商品
* @param goods
*/
public void addGoods(GoodsInfo goods) {
this.addGoods(goods,1);
}
/**
* 添加一种商品到购物车中,如果这种商品在购物车存在,
* 那就修改其数量
* 反之则构造一个新的对象,添加其对象中
* @param goods
* @param quantity:数量
*/
public void addGoods(GoodsInfo goods,int quantity) {
if(goods != null) { //当商品不为空的时候
OrderGoodsInfo orderGoods = null;
if(cart.containsKey(goods.getGoodsId())) { //表示当前商品存在
orderGoods = cart.get(Integer.valueOf(goods.getGoodsId()));
orderGoods.setQuantity(orderGoods.getQuantity() + quantity); //将原来的数量设置成现有的数量加上原来的数量
}else{
orderGoods = new OrderGoodsInfo();
orderGoods.setGoodsInfo(goods);
orderGoods.setQuantity(quantity);
cart.put(Integer.valueOf(goods.getGoodsId()), orderGoods);
}
}
}
/**
* 从购物车中移除商品(根据商品的id)
* @param id
* @return
*/
public boolean removeGoods(int id) {
//判断要移除的商品是否存在
if(cart.containsKey(Integer.valueOf(id))) {
cart.remove(Integer.valueOf(id));
return true;
}
return false;
}
/**
* 清空购物车的方法
*/
public void clearCart() {
if(this.cart != null) {
this.cart.clear();
}
}
/**
* 修改商品数量的方法
* @param goodId
* @param quantity
*/
public void updateQuantity(int goodsId,int quantity) {
if(cart.containsKey(goodsId)) {
OrderGoodsInfo orderGoods = cart.get(goodsId);
orderGoods.setQuantity(quantity);
}
}
/**
* 计算购物车中所有商品的价格
* @return
*/
public double getTotalPrice() {
double sum = 0.0; //总价
Iterator<Integer> iter = cart.keySet().iterator();
OrderGoodsInfo orderGoods = null;
//遍历购物车中所有的商品
while(iter.hasNext()) {
orderGoods = cart.get(iter.next());
sum += orderGoods.getSumPrice();
}
return Math.round(sum*100.0)/100.0;
}
}