14、模板方法模式(Template Method)

本文介绍了模板方法模式,它包含一个主方法和多个子方法。抽象类`AbstractCalculator`定义了主方法`calculate()`,该方法调用`split()`等辅助方法。子类如`Plus`和`Minus`继承抽象类并重写抽象方法。通过调用抽象类,实现了对具体计算逻辑的调用。测试类展示了模板方法模式的执行流程。
摘要由CSDN通过智能技术生成

14、模板方法模式(Template Method)

解释一下模板方法模式,就是指:一个抽象类中,有一个主方法,再定义1...n个方法,可以是抽象的,也可以是实际的方法,定义一个类,继承该抽象类,重写抽象方法,通过调用抽象类,实现对子类的调用,先看个关系图:

就是在AbstractCalculator类中定义一个主方法calculate,calculate()调用spilt()等,Plus和Minus分别继承AbstractCalculator类,通过对AbstractCalculator的调用实现对子类的调用,看下面的例子:

?
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
public abstract class AbstractCalculator {
   
  /*主方法,实现对本类其它方法的调用*/
  public final int calculate(String exp,String opt){
   int array[] = split(exp,opt);
   return calculate(array[0],array[1]);
  }
   
  /*被子类重写的方法*/
  abstract public int calculate( int num1, int num2);
   
  public int [] split(String exp,String opt){
   String array[] = exp.split(opt);
   int arrayInt[] = new int [ 2 ];
   arrayInt[ 0 ] = Integer.parseInt(array[ 0 ]);
   arrayInt[ 1 ] = Integer.parseInt(array[ 1 ]);
   return arrayInt;
  }
}
 
public class Plus extends AbstractCalculator {
  
  @Override
  public int calculate( int num1, int num2) {
   return num1 + num2;
  }
}

 测试类:

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

我跟踪下这个小程序的执行过程:首先将exp和"\\+"做参数,调用AbstractCalculator类里的calculate(String,String)方法,在calculate(String,String)里调用同类的split(),之后再调用calculate(int ,int)方法,从这个方法进入到子类中,执行完return num1 + num2后,将值返回到AbstractCalculator类,赋给result,打印出来。正好验证了我们开头的思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值