我是靠谱客的博主 奋斗舞蹈,这篇文章主要介绍设计模式 之 模板方法模式 使用场景 ,现在分享给大家,希望可以做个参考。

使用场景

  考虑一个计算存款利息的例子。假设系统需要支持两种存款账号,即货币市场(Money Market)账号和定期存款(Certificate of Deposite)账号。这两种账号的存款利息是不同的,因此,在计算一个存户的存款利息额时,必须区分两种不同的账号类型。

  这个系统的总行为应当是计算出利息,这也就决定了作为一个模板方法模式的顶级逻辑应当是利息计算。由于利息计算涉及到两个步骤:一个基本方法给出账号种类,另一个基本方法给出利息百分比。这两个基本方法构成具体逻辑,因为账号的类型不同,所以具体逻辑会有所不同。

  显然,系统需要一个抽象角色给出顶级行为的实现,而将两个作为细节步骤的基本方法留给具体子类实现。由于需要考虑的账号有两种:一是货币市场账号,二是定期存款账号。系统的类结构如下图所示。

源代码

  抽象模板角色类

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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; } }
具体模板角色类

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class MoneyMarketAccount extends Account { @Override protected String doCalculateAccountType() { return "Money Market"; } @Override protected double doCalculateInterestRate() { return 0.045; } }
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
public class CDAccount extends Account { @Override protected String doCalculateAccountType() { return "Certificate of Deposite"; } @Override protected double doCalculateInterestRate() { return 0.06; } }
客户端类

复制代码
1
2
3
4
5
6
7
8
9
10
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()); } }





最后

以上就是奋斗舞蹈最近收集整理的关于设计模式 之 模板方法模式 使用场景 的全部内容,更多相关设计模式内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(107)

评论列表共有 0 条评论

立即
投稿
返回
顶部