11.1 模板方法例子
考虑一个银行存款例子。假设系统需要支持两种存款账号,及货币市场账号(MoneyMarketAccount )和定期存款账号(CDAccount)。这两种账号的存款利息是不同的,因此在计算一个存户存款利息的时候,必须区分两种不同的账号。
这个系统的总行为是计算出利息,这个也就决定了两个步骤:一是确定账号类型,二是确定利息的百分比。因此系统需要两个基本方法:一个计算账号类型,一个计算利息百分比。
代码实现:
package test.biancheng.patterns.template.example1;
abstract public class Account
{
protected String accountNumber;
public Account()
{
accountNumber = null;
}
public Account(String accountNumber)
{
this.accountNumber = accountNumber;
}
final public double calculateInterest()
{
double interestRate = doCalculateInterestRate();
String accountType = doCalculateAccountType();
double amount = calculateAmount(accountType, accountNumber);
return amount * interestRate;
}
abstract protected String doCalculateAccountType() ;
abstract protected double doCalculateInterestRate() ;
final public double calculateAmount(String accountType, String accountNumber)
{
//retrieve amount from database...here is only a mock-up
return 7243.00D;
}
}
public class CDAccount extends Account
{
public String doCalculateAccountType()
{
return "Certificate of Deposite";
}
public double doCalculateInterestRate()
{
return 0.065D;
}
}
public class MoneyMarketAccount extends Account
{
public String doCalculateAccountType()
{
return "Money Market";
}
public double doCalculateInterestRate()
{
return 0.045D;
}
}
public class Client
{
private static Account acct = null;
public static void main(String[] args)
{
acct = new MoneyMarketAccount();
System.out.println("Interest earned from Money Market account = " + acct.calculateInterest());
acct = new CDAccount();
System.out.println("Interest earned from CD account = " + acct.calculateInterest());
}
}