1 abstract class getTime{
2 final public long doWork() {//final强制子类不能修改算法
3 long begin=System.currentTimeMillis();
4 //下面是子类的具体操作,通过父类回调。钩子方法。
5 count();
6 //父类的抽象方法
7 long end=System.currentTimeMillis();
8 return end-begin;
9 }
10 protected abstract void count();//只需要子类调用即可,外界不可调用
11 }
12 class CountString extends getTime{
13 public void count() {
14 String str="";
15 for(int i=0;i<10000;i++) {
16 str+=i;
17 }
18 }
19 }
20 class CountInt extends getTime{
21 public void count() {
22 int n=0;
23 for(int i=0;i<100000;i++) {
24 n+=1;
25 }
26 }
27 }
28 public class J5_Template {
29 public static void main(String[] args) {
30 System.out.println(new CountString().doWork());
31 System.out.println(new CountInt().doWork());
32 }
33 }
- 这里两个子类都具有一样的计算时间方法,所以通过父类将这个计算时间的方法抽象,子类实现各自的迭代。
- 在父类里面有两个方法,一个是计算时间的方法,另一个是抽象的子类中迭代的方法。同时,在计算时间的方法中,回调子类中迭代的抽象方法。
- 子类只需在各自的类中,细化这个迭代方法即可
- main入口调用的时候,直接用父类的方法即可。