package com.eric.行为型模式.模板方法模式.引例;
/**
* @author Eric
* @ProjectName my_design_23
* @description 抽象方法
* @CreateTime 2020-12-05 08:52:29
*/
public abstract class AbstractClass {
//基本方法
protected abstract void operation();
//模板方法
public void templateMethod()
{
//调用基本方法,完成相关的逻辑
this.operation();
}
}
package com.eric.行为型模式.模板方法模式.引例;
/**
* @author Eric
* @ProjectName my_design_23
* @description 具体模板方法
* @CreateTime 2020-12-05 08:54:45
*/
public class ConcreteClass extends AbstractClass {
//实现基本业务方法
@Override
protected void operation() {
//业务逻辑
System.out.println("具体的业务逻辑实现方法。");
}
}
package com.eric.行为型模式.模板方法模式.引例;
/**
* @author Eric
* @ProjectName my_design_23
* @description 测试类
* @CreateTime 2020-12-05 08:56:06
*/
public class Client {
public static void main(String[] args) {
AbstractClass concreteClass = new ConcreteClass();
//调用模板方法
concreteClass.templateMethod();
}
}
package com.eric.行为型模式.模板方法模式.例1;
import java.math.BigDecimal;
/**
* @author Eric
* @ProjectName my_design_23
* @description 抽象模板方法,抽象账户类
* @CreateTime 2020-12-05 12:46:29
*/
public abstract class Account {
//账号
private String username;
//构造函数
public Account(String username){
this.username = username;
}
//抽象方法,留给子类实现
//基本方法
//确定账户类型
public abstract String getAccountType();
//确定利息
public abstract double getAccountRate();
//根据账户类型和账号确定账户金额
public double getAccountMoney(String accountType,String username)
{
//模拟从数据库取值
return 3279.0D;
}
//模板方法,计算账户利息
public String calculateInterest(){
//获得账户类型
String accountType = getAccountType();
//获得比率
double accountRate = getAccountRate();
//获得账户余额
double accountMoney = getAccountMoney(accountType, username);
//账户余额*利率
return username+"账户的利息为"+accountMoney*accountRate;
}
}
package com.eric.行为型模式.模板方法模式.例1;
/**
* @author Eric
* @ProjectName my_design_23
* @description 活期存款
* @CreateTime 2020-12-05 13:05:49
*/
public class DemandAccount extends Account {
public DemandAccount(String username) {
super(username);
}
@Override
public String getAccountType() {
return "活期";
}
@Override
public double getAccountRate() {
return 0.005;
}
}
package com.eric.行为型模式.模板方法模式.例1;
/**
* @author Eric
* @ProjectName my_design_23
* @description 定期(1年)
* @CreateTime 2020-12-05 13:06:56
*/
public class FixedAccount extends Account {
public FixedAccount(String username) {
super(username);
}
@Override
public String getAccountType() {
return "定期一年";
}
@Override
public double getAccountRate() {
return 0.035;
}
}
package com.eric.行为型模式.模板方法模式.例1;
/**
* @author Eric
* @ProjectName my_design_23
* @description 测试类
* @CreateTime 2020-12-05 13:07:49
*/
public class Client {
public static void main(String[] args) {
//活期账户
Account demandAccount = new DemandAccount("张三");
System.out.println(demandAccount.calculateInterest());
// 定期账户
Account fixedAccount = new FixedAccount("王二麻子");
System.out.println(fixedAccount.calculateInterest());
}
}
原文:https://www.cnblogs.com/zyl-0110/p/14205841.html