模板方法模式

所有重复的代码都应该上升到父类去.
当我们要完成在某一细节层次一致的一个过程或一系列步骤,但其个别步骤在更详细的层次上的实现可能不同时,我们通常考虑用模板方法模式来处理.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package template.method;

/**
* Created by hero on 17-2-18.
*/
public abstract class TestPaper {
public void testQuestion1() {
System.out.println("小明是男是女?");
System.out.println("答案是: " + answer1());
}

public void testQuestion2() {
System.out.println("川普会被暗杀吗?");
System.out.println("答案是: " + answer2());
}

public abstract String answer1();

public abstract String answer2();
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package template.method;

/**
* Created by hero on 17-2-18.
*/
public class TestPaperA extends TestPaper {
public String answer1() {
return "随便";
}

public String answer2() {
return "可能";
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
package template.method;

/**
* Created by hero on 17-2-18.
*/
public class TestPaperB extends TestPaper {
public String answer1() {
return "男的啊";
}

public String answer2() {
return "不会";
}
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package template.method;

/**
* Created by hero on 17-2-18.
*/
public class Main {
public static void main(String[] args) {
TestPaper tp1 = new TestPaperA();
TestPaper tp2 = new TestPaperB();

tp1.testQuestion1();
tp1.testQuestion2();

tp2.testQuestion1();
tp2.testQuestion2();
}
}