1 20 21 package golfShop.business.cart; 22 23 import java.util.Stack ; 24 import java.util.Hashtable ; 25 import java.util.Enumeration ; 26 import golfShop.business.cart.CartItemPairImpl; 27 28 29 32 public class UndoRedoStack implements java.io.Serializable { 33 34 private Hashtable currentVersion; 35 private Stack undoStack; 36 private Stack redoStack; 37 38 53 protected UndoRedoStack (Hashtable initialVersion) { 54 undoStack = new Stack (); 55 redoStack = new Stack (); 56 currentVersion = copyHT(initialVersion); 57 } 58 59 67 protected void storeNewVersion (Hashtable newVersion) { 68 undoStack.push(currentVersion); 70 redoStack = new Stack (); 72 currentVersion = copyHT(newVersion); 74 } 75 76 protected boolean canUndo() { 77 return !undoStack.empty(); 78 } 79 80 protected Hashtable undoToPreviousVersion () { 81 if (undoStack.empty()) 82 return copyHT(currentVersion); 84 else { 85 redoStack.push(currentVersion); 87 currentVersion = (Hashtable ) undoStack.pop(); 89 return copyHT(currentVersion); 90 } 91 } 92 93 protected boolean canRedo() { 94 return !redoStack.empty(); 95 } 96 97 protected Hashtable redoToNewerVersion () { 98 if (redoStack.empty()) 99 return copyHT(currentVersion); 100 else { 101 undoStack.push(currentVersion); 102 currentVersion = (Hashtable ) redoStack.pop(); 103 return copyHT(currentVersion); 104 } 105 } 106 107 protected Object getCurrentVersion () { 108 return copyHT(currentVersion); 109 } 110 111 124 private Hashtable copyHT(Hashtable ht) { 125 Hashtable newHT = new Hashtable (); 126 Enumeration e = ht.keys(); 127 while (e.hasMoreElements()) { 128 Object key = e.nextElement(); 129 CartItemPairImpl value = (CartItemPairImpl) ht.get(key); 130 CartItemPairImpl valueCopy = value.copy(); 131 newHT.put(key, valueCopy); 132 } 133 return newHT; 134 } 135 136 private void printHT(Hashtable ht) { 138 Enumeration e = ht.keys(); 139 System.out.println("Hashtable contents:"); 140 while (e.hasMoreElements()) { 141 Object key = e.nextElement(); 142 CartItemPairImpl value = (CartItemPairImpl) ht.get(key); 143 System.out.println("ObjectId " + value.getItem().getObjectId() + 144 " x " + value.getQuantity()); 145 } 146 System.out.println("\n"); 147 } 148 } 149 150 151 152 | Popular Tags |