Home  >  Article  >  Java  >  Detailed explanation of template method pattern of java design pattern

Detailed explanation of template method pattern of java design pattern

怪我咯
怪我咯Original
2017-07-02 10:45:161303browse

This article mainly introduces the relevant information of the template method pattern of java design pattern in detail. It has certain reference value. Interested friends can refer to it

1. What is the template method pattern

Concept: Define the skeleton of an algorithm in an operation, and defer some steps to subclasses. Template methods allow subclasses to redefine specific steps of an algorithm without changing the structure of the algorithm.

In layman’s terms, the template method pattern realizes its advantages by moving unchanged behavior to the super class and removing duplicate code in the subclass. It provides a good code reuse platform. When immutable and mutable methods are mixed together in a subclass, the immutable method will appear multiple times in the subclass, so if one method needs to be modified, many methods need to be modified. Although this problem is This should be thought through at the beginning of the design. At this time, the template method pattern comes into play. Through the template method pattern, these recurring methods are moved to a single place, which can help subclasses get rid of the entanglement of repetition.

To give an easy-to-understand example, the author’s family was poor when I was a child. When I went to primary school in rural areas, every student had to hand-write the test papers because the school did not have test papers printed at that time. There were more than fifty students in the class. Each student had to copy the test paper on the blackboard repeatedly, and a short-sighted person like me could easily copy wrongly. 8 became 3, 7 became 1, etc., and then obviously got it right but The score was not high, which resulted in me always being at the bottom of the class. This is a very serious problem of duplication and immutability. Now the conditions are much better. Students do not need to copy test papers. The printing of test papers solves this problem of repeated copying of test papers. The template method is similar.

2. Comparison of modes

1. Copying test paper mode

The author uses the name of copying test paper mode to explain repetition Due to the inconvenience caused by the change, the model will be improved below.

The test paper copied by student A

public class TestPaperA {
 //试卷第一题
 public void testQuestion1(){
  System.out.println("小龙女是杨过的什么亲戚?() A.小姨妈 B.大姨妈 C.姑妈 D.舅妈");
  System.out.println("答案:C");
 }
 
 //试卷第二题
 public void testQuestion2(){
  System.out.println("全真教的首任掌门是谁?A.周伯通 B.欧阳锋 C.王重阳 D.西门吹牛");
  System.out.println("答案:C");
 }
 
 //试卷第三题
 public void testQuestion3(){
  System.out.println("《天龙八部》中被封为南院大王的大侠是谁?A.段誉 B.乔峰 C.慕容复 D.段智兴");
  System.out.println("答案:B");
 }
}

The test paper copied by student B

public class TestPaperB {
 //试卷第一题
 public void testQuestion1(){
  System.out.println("小龙女是杨过的什么亲戚?() A.小姨妈 B.大姨妈 C.姑妈 D.舅妈");
  System.out.println("答案:A");
 }
 
 //试卷第二题
 public void testQuestion2(){
  System.out.println("全真教的首任掌门是谁?A.周伯通 B.欧阳锋 C.王重阳 D.西门吹牛");
  System.out.println("答案:C");
 }
 
 //试卷第三题
 public void testQuestion3(){
  System.out.println("《天龙八部》中被封为南院大王的大侠是谁?A.段誉 B.乔峰 C.慕容复 D.段智兴");
  System.out.println("答案:D");
 }
}

Client code

public class ShowAnswer {

 public static void main(String[] args) {
  System.out.println("学生甲的试卷");
  TestPaperA stuA = new TestPaperA();
  stuA.testQuestion1();
  stuA.testQuestion2();
  stuA.testQuestion3();
  System.out.println("学生乙的试卷");
  TestPaperB stuB = new TestPaperB();
  stuB.testQuestion1();
  stuB.testQuestion2();
  stuB.testQuestion3();
 }

}

It is easy to find the test papers copied by the above two students There are a lot of repetitions, such as test paper questions and methods of outputting answers. These are all mixed together in each student test paper class, which is not conducive to maintenance or browsing. Let’s take a look at how the template method pattern has been improved. .

2. Template method mode

Extract the repeated parts of each student's test paper, questions, answers, etc.

First transform the test paper class and change the class to Abstract class. In this class, I added three abstract methods for subclass implementation, and students are required to answer. But the answers are different, so the answering process can be extracted as a repeated and unchanged method. The code is as follows.

public abstract class TestPaper {
 //试卷第一题
 public void testQuestion1(){
  System.out.println("小龙女是杨过的什么亲戚?() A.小姨妈 B.大姨妈 C.姑妈 D.舅妈");
  System.out.println("答案:" + answer1());
 }
 
 //试卷第二题
 public void testQuestion2(){
  System.out.println("全真教的首任掌门是谁?A.周伯通 B.欧阳锋 C.王重阳 D.西门吹牛");
  System.out.println("答案:" + answer2());
 }
 
 //试卷第三题
 public void testQuestion3(){
  System.out.println("《天龙八部》中被封为南院大王的大侠是谁?A.段誉 B.乔峰 C.慕容复 D.段智兴");
  System.out.println("答案:" + answer3());
 }
 
 //这三个钩子方法是给每个子类去实现,并返回答案的
 public abstract String answer1();
 public abstract String answer2();
 public abstract String answer3();
 
 //模板方法,考试的过程,定义基本的考试过程,子类回调
 public void exam(){
  testQuestion1();
  testQuestion2();
  testQuestion3();
 }
}

Let’s first look at the test situation of the first student

public class TestPaperA extends TestPaper{

 @Override
 public String answer1() {
  return "A";
 }

 @Override
 public String answer2() {
  return "B";
 }

 @Override
 public String answer3() {
  return "D";
 }
 
}

The answers to other students’ test papers may not be the same, but the basic answering process is the same, so I won’t repeat it. Let’s take a look at the client code.

public class ShowAnswer {

 public static void main(String[] args) {
  TestPaper testPaper = new TestPaperA();
  testPaper.exam();
 }

}

It can be seen that the client code has also been simplified a lot. This makes the logic clear and easy to maintain. The advantages are obvious. Let’s take a look at the specific answers.

What kind of relative is Xiao Longnu of Yang Guo? () A. Little aunt B. Great aunt C. Aunt D. Aunt
Answer: A
Who was the first head of the Quanzhen Sect? A. Zhou Botong B. Ouyang Feng C. Wang Chongyang D. Ximen Brag
Answer: B
Who is the hero who was named the King of the South Campus in "Dragon"? A. Duan Yu B. Qiao Feng C. Murong Fu D. Duan Zhixing
Answer: D

3. The basic structure of the template method pattern

AbstractClass It is an abstract class, which is actually an abstract template that defines and implements a template method. This template method is generally a concrete implementation, which gives some logical skeleton, and the composition of the logic is in the corresponding abstract class, which is postponed to the subclass implementation. The code is as follows

public abstract class AbstractClass {

 //一些抽象行为,可以理解为重复不变的方法,提取到抽象类
 public abstract void primitiveOperation1();
 public abstract void primitiveOperation2();
 
 //模板方法,给出了具体逻辑的骨架,而逻辑的组成是一些相应的抽象操作,他们都推迟到子类实现
 public void templateMothed(){
  primitiveOperation1();
  primitiveOperation2();
 }
 
}

ConcreteClass, which implements one or more abstract methods defined by the parent class. Each AbstractClass can have one or more ConcreteClass corresponding to it, and each ConcreteClass can provide different implementations of these abstract methods (that is, the steps of the skeleton), so the implementations obtained are different.

public class ConcreteClassA extends AbstractClass{

 @Override
 public void primitiveOperation1() {
  System.out.println("子类A的操作1");
 }

 @Override
 public void primitiveOperation2() {
  System.out.println("子类A的操作2");
 }

}
public class ConcreteClassB extends AbstractClass{

 @Override
 public void primitiveOperation1() {
  System.out.println("子类B的操作1");
 }

 @Override
 public void primitiveOperation2() {
  System.out.println("子类B的操作2");
 }

}

Two specific implementations are defined above. More implementations are actually the same, so I won’t go into details here. Let’s look at the client code

public class Show {

 public static void main(String[] args) {
  AbstractClass c;
  c = new ConcreteClassA();
  c.templateMothed();
  c = new ConcreteClassB();
  c.templateMothed();
 }
 
}

Enter the following

Operation 1 of subclass A
Operation 2 of subclass A
Operation 1## of subclass B #Operation of subclass B 2

##4. UML diagram


3. Summary


The template method pattern is to extract repetitive and unchanged code into an abstract class. When we want to complete a process or a series of steps that are consistent at a certain level of detail, but the implementation of individual steps may be different at a more detailed level, we usually consider using the template method pattern to deal with it.

The above is the detailed content of Detailed explanation of template method pattern of java design pattern. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn