Java Reference
In-Depth Information
Without a doubt, the observer pattern is one of the most useful patterns out there, especially since
it forms the cornerstone of another pattern: model‐view‐controller. You were introduced to this pat-
tern in the previous chapter on GUIs. Basically, a model‐view‐controller architecture expresses the
fact that every program should be separated in three loosely coupled parts:
The model as the central component containing the problem domain (accounts, users, and so
on). This part should be completely independent from the user interface in the sense that the
interface cannot directly manipulate the model.
The controller is the component that sends commands to the model to manipulate it.
The view is the interface through which the users get an output representation.
This description is a bit hand‐wavy, so it is illustrated here with a simple example. Say you want
to create a program to deal with checking accounts and you want to put a fancy GUI on top of
it. You could start by building a simple window and just keep adding lists and variables until
you have everything stuffed in a single ball of code spaghetti, but this is not the object‐oriented
way to do things. Instead, you start building the core problem domain and think about the
classes that matter. In this case, that would be an account. You may recall this example from
earlier:
public class Account {
private String name;
private double amount;
public Account(String name) {
this(name, 0);
}
public Account(String name, double startAmount) {
this.name = name;
this.amount = startAmount;
}
public boolean isOverdrawn() {
return this.amount < 0;
}
public void addFunds(double amount) {
this.amount += amount;
}
public String getName() {
return name;
}
public double getAmount() {
return amount;
}
}
Next up, you want to create a GUI to manage your account objects. You could start adding win-
dows to this class, but again, this does not seem like the right way to do it. Instead, you decide to
start with a new class:
Search WWH ::




Custom Search