设计模式总结篇系列:模板方法模式(Template Method)

模板方法模式需要开发抽象类和具体子类之间的协作。抽象类负责给出一个算法的轮廓和骨架,子类则负责给出这个算法的各个逻辑步骤。代表这些具体逻辑步骤的方法称做基本方法(primitive method);而将这些基本方法汇总起来的方法叫做模板方法(template method)。子类重写抽象类中的抽象方法,通过调用抽象类中的模板方法中的抽象方法,实现对子类基本方法的调用。

直接来看一个例子:

1.定义一个抽象类,及类中的模板方法和抽象方法:

 1 abstract class AbstractCalculator {
 2 
 3     // 主方法,实现对本类其它方法的调用
 4     public final int getResult(String exp, String opt) {
 5         int array[] = split(exp, opt);
 6         return calculate(array[0], array[1]);
 7     }
 8 
 9     public int[] split(String exp, String opt) {
10         String array[] = exp.split(opt);
11         int arrayInt[] = new int[2];
12         arrayInt[0] = Integer.parseInt(array[0]);
13         arrayInt[1] = Integer.parseInt(array[1]);
14         return arrayInt;
15     }
16 
17     // 被子类重写的方法
18     abstract public int calculate(int num1, int num2);
19 }

2.定义子类:

1 class Plus extends AbstractCalculator {  
2       
3     @Override  
4     public int calculate(int num1,int num2) {  
5         return num1 + num2;  
6     }  
7 }  

3.测试:

1 public class TemplateMethodTest {
2 
3     public static void main(String[] args) {
4         String exp = "5+8";
5         AbstractCalculator cal = new Plus();
6         int result = cal.getResult(exp, "\\+");
7         System.out.println(result);
8     }
9 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值