1 package org.prevayler.demos.demo2.business; 2 3 import java.util.*; 4 5 public class Account implements java.io.Serializable { 6 7 private long number; 8 private String holder; 9 private long balance = 0; 10 private List transactionHistory = new ArrayList(); 11 private transient Set listeners; 12 13 private Account() { 14 } 15 16 Account(long number, String holder) throws InvalidHolder { 17 this.number = number; 18 holder(holder); 19 } 20 21 public long number() { 22 return number; 23 } 24 25 public String toString() { return numberString() + " - " + holder; 27 } 28 29 public String numberString() { 30 return numberString(number); 31 } 32 33 static String numberString(long number) { 34 return (new java.text.DecimalFormat ("00000").format(number)); 35 } 36 37 public String holder() { 38 return holder; 39 } 40 41 public void holder(String holder) throws InvalidHolder { 42 verify(holder); 43 this.holder = holder; 44 notifyListeners(); 45 } 46 47 public long balance() { 48 return balance; 49 } 50 51 public void deposit(long amount, Date timestamp) throws InvalidAmount { 52 verify(amount); 53 register(amount, timestamp); 54 } 55 56 public void withdraw(long amount, Date timestamp) throws InvalidAmount { 57 verify(amount); 58 register(-amount, timestamp); 59 } 60 61 private void register(long amount, Date timestamp) { 62 balance += amount; 63 transactionHistory.add(new AccountEntry(amount, timestamp)); 64 notifyListeners(); 65 } 66 67 private void verify(long amount) throws InvalidAmount { 68 if (amount <= 0) throw new InvalidAmount("Amount must be greater than zero."); 69 if (amount > 10000) throw new InvalidAmount("Amount maximum (10000) exceeded."); 70 } 71 72 public List transactionHistory() { 73 return transactionHistory; 74 } 75 76 public void addAccountListener(AccountListener listener) { 77 listeners().add(listener); 78 } 79 80 public void removeAccountListener(AccountListener listener) { 81 listeners().remove(listener); 82 } 83 84 private Set listeners() { 85 if (listeners == null) listeners = new HashSet(); 86 return listeners; 87 } 88 89 private void notifyListeners() { 90 Iterator it = listeners().iterator(); 91 while (it.hasNext()) { 92 ((AccountListener)it.next()).accountChanged(); 93 } 94 } 95 96 public class InvalidAmount extends Exception { 97 InvalidAmount(String message) { 98 super(message); 99 } 100 } 101 102 private void verify(String holder) throws InvalidHolder { 103 if (holder == null || holder.equals("")) throw new InvalidHolder(); 104 } 105 106 public class InvalidHolder extends Exception { 107 InvalidHolder() { 108 super("Invalid holder name."); 109 } 110 } 111 } 112 | Popular Tags |