文章目录
模板模式定义
每一件事情有固定的步骤,但是步骤的具体实现不同,在父类中完成该事情的总方法,具体的细节有子类完成.
模板方法有两个角色组成:
抽象父类: 事情的总方法
具体类: 具体执行总方法的实现细节的子类
定义一个抽象父类:
public abstract class Account {
/**
* 模板方法,计算利息数额
* @return 返回利息数额
*/
public final double calculateInterest(){
double interestRate = doCalculateInterestRate();
String accountType = doCalculateAccountType();
double amount = calculateAmount(accountType);
return amount * interestRate;
}
/**
* 基本方法留给子类实现
*/
protected abstract String doCalculateAccountType();
/**
* 基本方法留给子类实现
*/
protected abstract double doCalculateInterestRate();
/**
* 基本方法,已经实现
*/
private double calculateAmount(String accountType){
/**
* 省略相关的业务逻辑
*/
return 7243.00;
}
}
具体类
货币市场账号
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 of Deposite";
}
@Override
protected double doCalculateInterestRate() {
return 0.06;
}
}
客户端类:
public class Client {
public static void main(String[] args) {
Account account = new MoneyMarketAccount();
System.out.println("货币市场账号的利息数额为:" + account.calculateInterest());
account = new CDAccount();
System.out.println("定期账号的利息数额为:" + account.calculateInterest());
}
}