项目第六阶段:购物车
购物车模块分析
购物车模型编写
购物车模型
package com.sq.pojo;
import java.math.BigDecimal;
public class CartItem {
private Integer id;
private String name;
private Integer count;
private BigDecimal price;
private BigDecimal totalPrice;
public CartItem() {
}
public CartItem(Integer id, String name, Integer count, BigDecimal price, BigDecimal totalPrice) {
this.id = id;
this.name = name;
this.count = count;
this.price = price;
this.totalPrice = totalPrice;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public BigDecimal getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
@Override
public String toString() {
return "CartItem{" +
"id=" + id +
", name='" + name + '\'' +
", count=" + count +
", price=" + price +
", totalPrice=" + totalPrice +
'}';
}
}
package com.sq.pojo;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class Cart {
private BigDecimal totalPrice;
private Map<Integer,CartItem> items = new LinkedHashMap<Integer,CartItem>();
public void addItem(CartItem cartItem){
CartItem item = items.get(cartItem.getId());
if (item == null){
items.put(cartItem.getId(),cartItem);
} else {
item.setCount( item.getCount() + 1 );
item.setTotalPrice( item.getPrice().multiply(new BigDecimal( item.getCount() )) );
}
}
public void deleteItem(Integer id){
items.remove(id);
}
public void clear(){
items.clear();
}
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() )) );
}
}
public Integer getTotalCount() {
Integer totalCount = 0;
for (Map.Entry<Integer,CartItem>entry : items.entrySet()){
totalCount += entry.getValue().getCount();
}
return totalCount;
}
public BigDecimal getTotalPrice() {
BigDecimal totalPrice = new BigDecimal(0);
for (Map.Entry<Integer,CartItem>entry : items.entrySet()){
totalPrice = totalPrice.add(entry.getValue().getTotalPrice());
}
return totalPrice;
}
public void setTotalPrice(BigDecimal totalPrice) {
this.totalPrice = totalPrice;
}
public Map<Integer, CartItem> getItems() {
return items;
}
public void setItems(Map<Integer, CartItem> items) {
this.items = items;
}
@Override
public String toString() {
return "Cart{" +
"totalCount=" + getTotalCount() +