import java.util.Enumeration; import java.util.Hashtable; public class ShoppingBasketImpl implements ShoppingBasket { private Hashtable m_basket; private ItemFactory m_itemFactory; public ShoppingBasketImpl(ItemFactory itemFactory) { Util.assert(itemFactory != null, "Null Item Factory is not allowed"); m_basket = new Hashtable(); m_itemFactory = itemFactory; } public void addItem(Item newItem) { Util.assert(newItem != null, "Invalid newItem to add to Basket"); int newQuantity = 0; Item oldItem = (Item) m_basket.remove(newItem.getItemId()); /* If newItem is not in the shopping basket (ie. oldItem==null) then * we add it. * Otherwise, we add a BRAND NEW item * whose quantity is newItem.quantity + oldItem.quantity */ if (oldItem == null) { m_basket.put(newItem.getItemId(), newItem); } else { /* Notice that oldItem.equals(newItem) is true which * means that unit price, id, name are the same for both * oldItem and newItem. * * We remove the old item and add in a new one. Why don't * we just get the old one and modify it? Because someone * could modify ItemImpl.hashCode() so that it depends * on quantity. */ newQuantity = oldItem.getQuantity() + newItem.getQuantity(); Item item = m_itemFactory.createItem( oldItem.getItemId(), // same as newItem.getItemId() oldItem.getItemName(), // same as newItem.getItemName() newQuantity, oldItem.getUnitPrice()); // same as newItem.getUnitPrice() m_basket.put(item.getItemId(), item); } } //end addItem public void removeItem(Item deletedItem) { /* We remove the item and add it back in if necessary because * the hashCode might change. */ int newQuantity = 0; Item removedItem = (Item) m_basket.remove(deletedItem.getItemId()); Util.assert(removedItem != null, "Tried to remove an item that is not in the basket"); newQuantity = removedItem.getQuantity() - deletedItem.getQuantity(); Util.assert(newQuantity >= 0, "Tried to remove more " + removedItem.getItemName() + "s" + " then actually exist in the basket"); if (newQuantity > 0) { Item item = m_itemFactory.createItem(removedItem.getItemId(), removedItem.getItemName(), newQuantity, removedItem.getUnitPrice()); m_basket.put(item.getItemId(), item); } } //end removeItem public Enumeration elements() { return m_basket.elements(); } public String toString() { float total = 0.0F; Enumeration e = m_basket. elements (); String r = ""; Item anItem; while (e. hasMoreElements ()) { anItem = (Item) e. nextElement (); total = total + anItem. getTotalPrice (); r = r + anItem. toString () + "\n"; } r = r + "TOTAL: $" + total; return r; } }