KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > opensymphony > webwork > example > ajax > cart > DefaultCart


1 /*
2  * Copyright (c) 2005 Your Corporation. All Rights Reserved.
3  */

4 package com.opensymphony.webwork.example.ajax.cart;
5
6 import com.opensymphony.webwork.example.ajax.catalog.Product;
7
8 import java.util.HashMap JavaDoc;
9 import java.util.HashSet JavaDoc;
10 import java.util.Map JavaDoc;
11 import java.util.Set JavaDoc;
12
13 /**
14  * DefaultCart
15  *
16  * @author Jason Carreira <jcarreira@eplus.com>
17  */

18 public class DefaultCart implements ShoppingCart {
19     Map JavaDoc contents = new HashMap JavaDoc();
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 JavaDoc getContents() {
50         return new HashSet JavaDoc(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 JavaDoc 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