模板方法模式(抽取)
public class TestPaper {
public void question1() {
System.out.println("question1");
}
public void question2() {
System.out.println("question2");
}
}
//学生A抄的试卷,带答试题和答案
public class TestPaperA extends TestPaper{
public void question1() {
super.question1();
System.out.println("answer1");
}
public void question2() {
super.question2();
System.out.println("answer2");
}
}
//学生B抄的试卷,带答试题和答案
public class TestPaperB extends TestPaper{
public void question1() {
super.question1();
System.out.println("answer1");
}
public void question2() {
super.question2();
System.out.println("answer2");
}
}
public class Demo1 {
public static void main(String[] args) {
System.out.println("学生A抄写的试卷");
TestPaper a=new TestPaperA();
a.question1();
a.question2();
System.out.println("学生B抄写的试卷");
TestPaper b=new TestPaperB();
b.question1();
b.question2();
}
}
两个子类中有相同的东西super.question1(),super.question2(),可以向上抽取,把重复的代码放在父类中,而不是让每个子类都去重复.
public class Paper {
public void question1() {
System.out.println("question1");
System.out.println(answer1());
}
//此方法的目的就是给继承的子类重写,因为这里每个人的答案都是不同的
public String answer1() {
return "";
}
public void question2() {
System.out.println("question2");
System.out.println(answer2());
}
//此方法的目的就是给继承的子类重写,因为这里每个人的答案都是不同的
public String answer2() {
return "";
}
}
public class PaperA extends Paper{
public String answer1() {
return "answer1";
}
public String answer2() {
return "answer2";
}
}
public class PaperB extends Paper {
public String answer1() {
return "answer1";
}
public String answer2() {
return "answer2";
}
}
public class Demo2 {
public static void main(String[] args) {
System.out.println("学生A抄写的试卷");
Paper a=new PaperA();
a.question1();
a.question2();
System.out.println("学生B抄写的试卷");
Paper b=new PaperB();
b.question1();
b.question2();
}
}
模板方法模式提供了一个很好的代码复用平台,当不变和可变的行为在方法的子类实现中混合在一起的时候,不变的行为就会在子类中重复出现,通过模板方法模式把这些不变的行为移到超类中,去除子类中重复的代码