Java Reference
In-Depth Information
Try It Out - Defining a Bank Class
The bank computer is the agent that will perform the operations on an account so we will start with that.
We can define the
Bank
class that will represent this as:
// Define the bank
class Bank {
// Perform a transaction
public void doTransaction(Transaction transaction) {
int balance = transaction.getAccount().getBalance(); // Get current balance
switch(transaction.getTransactionType()) {
case Transaction.CREDIT:
// Credits require a lot of checks...
try {
Thread.sleep(100);
} catch(InterruptedException e) {
System.out.println(e);
}
balance += transaction.getAmount(); // Increment the balance
break;
case Transaction.DEBIT:
// Debits require even more checks...
try {
Thread.sleep(150);
} catch(InterruptedException e) {
System.out.println(e);
}
balance -= transaction.getAmount(); // Decrement the balance
break;
default: // We should never get here
System.out.println("Invalid transaction");
System.exit(1);
}
transaction.getAccount().setBalance(balance); // Restore the account balance
}
}
How It Works
The
Bank
class is very simple. It keeps no records of anything locally as the accounts will be identified
separately, and it only has one method that carries out a transaction. The
Transaction
object will
provide all the information about what the transaction is, and to which account it applies. We have only
provided for debit and credit operations on an account, but the switch could easily be extended to
accommodate other types of transactions. Both of the transactions supported involve some delay while
the standard nameless checks and verifications, that all banks have, are carried out. The delay is
simulated by calling the
sleep()
method belonging to the
Thread
class.