模板方法模式是基于继承的代码复用的基本技术。
模板方法模式需要开发抽象类和具体子类的设计师之间的协作,一个设计师负责给出一个算法的轮廓和骨架,另一些设计师负责给出这个算法的各个逻辑步骤。
//抽象模板角色类
public abstract class Account
{
//模板方法
public final double calculateInterest()
{
double interestRate = doCalculateInterestRate();
String accountType = doCalculateAccount();
double amount = calculateAmount(accountType);
return amount*interestRate;
}
//基本方法留给子类实现
protected abstract String doCalculateAccountType();
protected abstract double doCalculateInterestRate();
private double calculateAmount(String type)
{
return 5000.0;
}
}
//具体子类实现类
public class MoneyMarketAccount extends Account
{
@override
protected String doCalculateAccountType()
{
return "Money Market";
}
@override
protected double doCalculateInterestRate()
{
return 0.045;
}
}
public class CDAccount extends Account
{
@override
protected String doCalculateAccountType()
{
return "Certificate Deposite";
}
@override
protected double doCalculateInterestRate()
{
return 0.06;
}
}
模板模式的关键是:子类可以置换掉父类的可变部分,但是子类却不可以改变模板方法所代表的顶级逻辑。