📄 shoppingcart.java
字号:
package netstore.framework;
import java.util.List;
import java.util.LinkedList;
/**
* 购物车类
*
* @author huangyongfeng
*
*/
public class ShoppingCart {
/**
* 新增一个产品
*
* @param newItem
*/
public void addItem(ShoppingCartItem newItem) {
// Check to see if this item is already present, if so, inc the qty
int size = getSize();
ShoppingCartItem cartItem = findItem(newItem.getId());
//看产品是否已经存在
if (cartItem != null) {
//更新产品数量
cartItem.setQuantity(cartItem.getQuantity() + newItem.getQuantity());
} else {
// Must have been a different item, so add it to the cart
//加入新的产品
items.add(newItem);
}
}
public void setItems(List otherItems) {
items.addAll(otherItems);
}
public ShoppingCart() {
items = new LinkedList();
}
public void setSize(int size) {
// The size is really determined by the list.
// This is needed so that it can act as a JavaBean with a get/set.
}
public void empty() {
items.clear();
}
//获取总价
public double getTotalPrice() {
double total = 0.0;
int size = items.size();
for (int i = 0; i < size; i++) {
total += ((ShoppingCartItem) items.get(i)).getUnitPrice();
}
return total;
}
//删除某种产品
public void removeItem(Long itemId) {
int size = getSize();
ShoppingCartItem item = findItem(itemId);
if (item != null) {
items.remove(item);
}
}
public void removeItems(List itemIds) {
if (itemIds != null) {
int size = itemIds.size();
for (int i = 0; i < size; i++) {
removeItem(new Long((String) itemIds.get(i)));
}
}
}
public void updateQuantity(Long itemId, int newQty) {
ShoppingCartItem item = findItem(itemId);
if (item != null) {
item.setQuantity(newQty);
}
}
public int getSize() {
return items.size();
}
public List getItems() {
return items;
}
private ShoppingCartItem findItem(Long itemId) {
ShoppingCartItem item = null;
int size = getSize();
for (int i = 0; i < size; i++) {
ShoppingCartItem cartItem = (ShoppingCartItem) items.get(i);
if (itemId.equals(cartItem.getId())) {
item = cartItem;
break;
}
}
return item;
}
//产品链表
private List items = null;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -