?? shoppingcart.java
字號(hào):
package ajax.biz;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class ShoppingCart {
private Map cartMap = null; //保存Product的Map
/**
* 購物車構(gòu)造函數(shù)
*/
public ShoppingCart() {
cartMap = new HashMap();
}
/**
* 檢查是否購物車內(nèi)已存在該產(chǎn)品
*/
public boolean existProduct(String productId) {
Iterator hmKey = cartMap.keySet().iterator();
while (hmKey.hasNext()) {
String hmId = (String) hmKey.next();
if (hmId.equals(productId)) {
return true;
}
}
return false;
}
/**
* 取得存放產(chǎn)品的cartMap
*/
public Map getCartMap() {
return cartMap;
}
/**
* 取得購物車內(nèi)產(chǎn)品總數(shù)量
*/
public int getProductsNum() {
int productNum = 0;
Iterator hmEntry = cartMap.values().iterator();
while (hmEntry.hasNext()) {
productNum += ((Product) hmEntry.next()).getProductsNum();
}
return productNum;
}
/**
* 添加產(chǎn)品進(jìn)購物車
*/
public boolean addProduct(String productId) {
if (existProduct(productId)) {// 產(chǎn)品已存在則增加數(shù)量
Product product = (Product) cartMap.get(productId);
product.setProductsNum(product.getProductsNum() + 1);
return true;
} else {// 否則新加入該產(chǎn)品
Product product = new Product(productId);
if (product.getProductId() == null) {
return false;
} else {
cartMap.put(productId, product);
return true;
}
}
}
/**
* 刪除購物車內(nèi)產(chǎn)品
*/
public void delProduct(String productId) {
cartMap.remove(productId);
}
/**
* 取得購物車內(nèi)產(chǎn)品總計(jì)金額
*/
public double getTotalPrice() {
double totalPrice = 0;
Iterator hmEntry = cartMap.values().iterator();
while (hmEntry.hasNext()) {
Product product = (Product) hmEntry.next();
totalPrice += product.getProductsNum() * product.getProductPrice();
}
return totalPrice;
}
/**
* 清空購物車
*/
public void clearProduct() {
cartMap.clear();
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -