Java Reference
In-Depth Information
}
public void setAmount(double amount) {
this.amount = amount;
}
}
public class AccountManager {
public Account createAccount(String name, double startFunds) {
Account account = new Account();
account.setName(name);
account.setAmount(startFunds);
return account;
}
public boolean isOverdrawn(Account account) {
return account.getAmount() < 0;
}
public void addFunds(Account account, double amount) {
account.setAmount(account.getAmount() + amount);
}
}
This example can look a bit silly—rightly so—although note that there exist many cases of code
with such anti‐object‐oriented design once you look behind the curtain. In cases such as these, it's
easy to imagine that AccountManager should be a singleton. Any account will need a manager,
and how many managers do you need? Of course, the correct answer is not one, but none. You can
resolve this problem like so:
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;
}
Search WWH ::




Custom Search