the design of the shopping Cart:
Package com.shop.cart.vo;
Import java.util.Collection;
Import Java.util.LinkedHashMap;
Import Java.util.Map; /** * Shopping Cart Object * * * @author Charlotte * */public class Cart {//Shopping item: Key: Product pid, Value: Shopping Item private Map<integer, Ca
rtitem> map = new Linkedhashmap<integer, cartitem> ();
There is one in the Cart object called Cartitems property public collection<cartitem> Getcartitems () {return map.values ();
//Shopping Totals: private double total;
Gettotal method public Double Gettotal () {return total; }//Shopping cart function//1. Add a shopping item to the shopping cart public void Addcart (Cartitem cartitem) {//To determine if the shopping cart already exists/* * If present: * Quantity increased * total = total + Shopping Total * If not present: * to
Add shopping items in Map * total = total + Shopping Item Subtotal//Get the Product ID Integer pid = cartitem.getproduct (). Getpid (); Determine if the shopping item if (Map.containskey (PID)) {//exists cartitem _cartitem = Map.get (PID);//Get the original shopping item in the cart _cartitem.set
Count (_cartitem.getcount () + cartitem.getcount ());
else {//does not exist Map.put (PID, Cartitem); }//Set total value = Cartitem.getsubTotal ();
//2. To remove a shopping item from the shopping cart public void Removecart (Integer pid) {//Remove shopping items from shopping cart cartitem Cartitem = map.remove (PID);
Total = grand Totals-Subtotal Total-= Cartitem.getsubtotal () to remove a shopping item;
//3. Empty the shopping cart public void Clearcart () {//Empty map.clear () of all shopping items;
Set Totals to 0 total = 0;
}
}
Shopping Item Object Design:
Package Com.shop.cart.vo;
Import cn.itcast.shop.product.vo.Product;
/**
* Shopping Item Object
*
* * @author Charlotte */Public
class Cartitem {
private Product product;// Item information in the shopping item
private int count;//Buy a quantity of a commodity
private double subtotal;//Buy a subtotal public product getproduct for a product
( ) {return
product;
}
public void Setproduct (product product) {
this.product = product;
}
public int GetCount () {return
count;
}
public void SetCount (int count) {
This.count = count;
}
Subtotal automatic calculation public
double Getsubtotal () {return
count * Product.getshop_price ();
}
/* public void setsubtotal (double subtotal) {this.subtotal = subtotal;}
*/
}