1 4 package com.opensymphony.webwork.example.ajax.cart; 5 6 import com.opensymphony.webwork.example.ajax.catalog.Product; 7 8 import java.util.HashMap ; 9 import java.util.HashSet ; 10 import java.util.Map ; 11 import java.util.Set ; 12 13 18 public class DefaultCart implements ShoppingCart { 19 Map contents = new HashMap (); 20 21 public void addToCart(int quantity, Product product) { 22 CartEntry entry = (CartEntry) contents.get(product); 23 if (entry == null) { 24 entry = new DefaultCartEntry(quantity, product); 25 contents.put(product, entry); 26 } else { 27 entry.setQuantity(entry.getQuantity() + quantity); 28 } 29 } 30 31 public void setQuantity(int quantity, Product product) { 32 if (quantity <= 0) { 33 contents.remove(product); 34 return; 35 } 36 CartEntry entry = (CartEntry) contents.get(product); 37 if (entry == null) { 38 entry = new DefaultCartEntry(quantity, product); 39 contents.put(product, entry); 40 } else { 41 entry.setQuantity(quantity); 42 } 43 } 44 45 public void removeFromCart(Product product) { 46 contents.remove(product); 47 } 48 49 public Set getContents() { 50 return new HashSet (contents.values()); 51 } 52 53 public int getQuantityForProduct(Product product) { 54 CartEntry entry = (CartEntry) contents.get(product); 55 if (entry == null) { 56 return 0; 57 } 58 return entry.getQuantity(); 59 } 60 61 public String toString() { 62 return "DefaultCart{" + 63 "contents=" + contents + 64 "}"; 65 } 66 67 class DefaultCartEntry implements CartEntry { 68 private int quantity; 69 private Product product; 70 71 public DefaultCartEntry(int quantity, Product product) { 72 this.quantity = quantity; 73 this.product = product; 74 } 75 76 public int getQuantity() { 77 return quantity; 78 } 79 80 public void setQuantity(int quantity) { 81 this.quantity = quantity; 82 } 83 84 public Product getProduct() { 85 return product; 86 } 87 } 88 } 89 | Popular Tags |