模板方法模式
模板方法模式主要是在完成某一细节层次中一致的一个过程,就是有多个业务会使用到这个方法,但是在这一个方法也就是这个一致的过程中有部分细节不同,这时用模板方法模式。
上面的结构图,是用了两种方式一种接口的方式,一种抽象方法的方式
抽象方法的写法
package example;
/**
* @Program: 设计模式
* @Description: 定义相同的过程的方法testQuest(),在细节上不同用抽象方法隔离出来,交给子类具体实现
* @Author Mokairui
* @Date 2020/12/20 22:02
*/
public abstract class TestPaper {
public void testQuestion1() {
System.out.println("题目一, 答案:" + answer1());
}
public void testQuestion2() {
System.out.println("题目二, 答案:" + answer2());
}
public void testQuestion3() {
System.out.println("题目三, 答案:" + answer3());
}
protected abstract String answer1();
protected abstract String answer2();
protected abstract String answer3();
}
实现上面的抽象方法,完成细节方法的重写
package example;
/**
* @Program: 设计模式
* @Description:
* @Author Mokairui
* @Date 2020/12/20 22:14
*/
public class StudentA extends TestPaper {
@Override
protected String answer1() {
return "A";
}
@Override
protected String answer2() {
return "B";
}
@Override
protected String answer3() {
return "C";
}
}
测试
TestPaper paper = new StudentA();
paper.testQuestion1();
paper.testQuestion2();
paper.testQuestion3();
接口实现
package example;
/**
* @Program: 设计模式
* @Description: 接口中使用默认方法定义过程,让实现类来完成细节的重写
* @Author Mokairui
* @Date 2020/12/20 22:16
*/
public interface ITest {
default void question1() {
System.out.println("题目一:XXXXXX");
System.out.println("答案:" + answer());
}
String answer();
}
package example;
/**
* @Program: 设计模式
* @Description:
* @Author Mokairui
* @Date 2020/12/20 22:17
*/
public class TestImpl implements ITest {
@Override
public String answer() {
return "选择A";
}
}
ITest demo = new TestImpl();
demo.question1();