Java Reference
In-Depth Information
serviced with a single line of code. It is ugly now, and enhancements—such as
checking for an overdrawn state, adding a customer name and number, and
attaching this program to a database or transaction—will keep the snowball
rolling. Adding on the functionality of the account number verification will
just exacerbate the problem.
3.1.4
Breaking out the model
Now, consider the first refactoring step in listing 3.2, the alternative:
Listing 3.2
The Model-View-Controller design pattern
This bank account program is the model portion for the same application as listing 3.1, refac-
tored to the Model-View-Controller design pattern.
public class Account {
o Model logic
private float balance;
public Account(float openingBalance) {
setBalance(openingBalance);
}
public void setBalance(float amount) {
this.balance=amount;
}
public float(get.balance) {
return this.balance
}
public float debit(float amount) {
setBalance(this.balance-amount);
return (this.balance);
}
public float credit(float amount) {
setBalance(this.balance+amount);
return (this.balance);
}
}
The revised program is much simpler. It is the model for the application. The
name of the class is a real business object. The methods represent real business
actions. We can do things that we would expect to do to an account, like debit
and credit and check the balance. The logic that handles events for the user
interface and marshals the data to the user interface does not belong with the
model. We would add a controller object to handle these functions.
Search WWH ::




Custom Search