一个抽象类,将部分逻辑以具体方法以及构造子的形式实现,然后声明一些抽象方法来迫使子类实现剩余的逻辑。不同的子类可以以不同的方式实现这些抽象方法,从而对剩余的逻辑有不同的实现
public abstract class Account {
protected String accountNumber;
public Account() {
}
public Account(String accountNumber) {
this.accountNumber = accountNumber;
}
/**
* 模板方法
*/
public double calculateInterest() {
double interestRate = doCalculateInterestRate();
String accountType = doCalculateAccountType();
double amount = calculateAmount(accountType, accountNumber);
return amount * interestRate;
}
protected abstract double doCalculateInterestRate();
protected abstract String doCalculateAccountType();
/**
* 基本方法
*/
public double calculateAmount(String accountType, String accountNumber) {
return 1000.00D;
}
}
public class MoneyMarketAccount extends Account {
@Override
protected String doCalculateAccountType() {
return "Money Market";
}
@Override
protected double doCalculateInterestRate() {
return 0.24D;
}
}
public class CDAccount extends Account {
@Override
protected String doCalculateAccountType() {
return "Certificate of Deposite";
}
@Override
protected double doCalculateInterestRate() {
return 0.35D;
}
}
public class Client {
private static Account acct = null;
public static void main(String[] args) {
acct = new MoneyMarketAccount();
System.out.println(acct.calculateInterest());
acct = new CDAccount();
System.out.println(acct.calculateInterest());
}
}