Source of BankAccountModel.java


  1: // BankAccountModel.java
  2: // Adapted from an example by Tony Sintes.
  3: // The BankAccountModel manages the account's state and behavior.
  4: // It also tracks any object interested in receiving state change 
  5: // notifications.

  7: import java.util.ArrayList;
  8: import java.util.Iterator;

 10: public class BankAccountModel
 11: {
 12:     // Private data
 13:     private double balance;
 14:     private ArrayList listeners = new ArrayList();
 15:     
 16:     public BankAccountModel(double initDeposit)
 17:     {
 18:         setBalance(initDeposit);
 19:     }

 21:     protected void setBalance(double newBalance)
 22:     {
 23:         balance = newBalance;
 24:         updateObservers();
 25:     }
 26:     
 27:     public double getBalance()
 28:     {
 29:         return balance;
 30:     }

 32:     public void depositFunds(double amount)
 33:     {
 34:         setBalance(getBalance() + amount);
 35:     }

 37:     public void withdrawFunds(double amount)
 38:     {
 39:         if (amount > getBalance()) 
 40:             amount = getBalance();
 41:         setBalance(getBalance() - amount);
 42:     }

 44:     // Places an Observer in the ArrayList of all observers.
 45:     public void register(Observer o)
 46:     {
 47:         listeners.add(o);  
 48:         o.update();
 49:     }

 51:     // Updates each Observer according to its own update() method.
 52:     // In our case there is actually only one Observer
 53:     private void updateObservers()
 54:     {
 55:         Iterator i = listeners.iterator();
 56:         while (i.hasNext())
 57:         {
 58:             Observer o = (Observer) i.next();
 59:             o.update();
 60:         }
 61:     }
 62: }