Big event
Friends who pay attention to basketball or like to visit social networking sites may know that on October 5, 2019, NBA Houston Rockets general manager Morey posted an ignorant picture of Hong Kong related affairs on twitter, which aroused strong protest and dissatisfaction from all Chinese people. For a while, public opinion was furious. After that, NBA President Xiao Hua responded that he supported Morey at this time and again exploded public opinion. It's been a week since the incident developed. The main contradiction maker, Party Morey and joke have no apology or regret, and even transfer the contradiction to various groups between the two countries. His arrogant attitude, sinister intentions, and blatant interference in his domestic politics and sovereignty integrity will definitely not give up this time.
These days, twitter, Weibo, Hupu, Zhihu and other major websites are all full of fighting because of this incident. Netizens are all smart under the news about this incident, using all their powers to solve the problem. There are endless comments and obscene remarks. Here, we also ask our compatriots not to be reviled by the people with bad intentions. We just need to grasp the main contradictions. Morey must apologize, resign from the position of general manager of the Rockets. Xiao Hua must also apologize and dismiss Morey. This is the most basic sincerity of apology, and it is possible to redeem the hearts of Chinese fans.
Of course, time will finally give us an answer. In the days waiting for the answer, there will be more and more people from all walks of life around the world who will voice on this matter. Of course, we will not be idle. We will "greet" Morey every day on major social media software to express our "freedom of speech".
This is two tweets about Morey after Lakers player James was interviewed by the media today. At present, the following comments are all on him. It can be said that inside and outside are not people. However, this is not the focus of this article. As a technical public account, let's think about it from the perspective of technology. Since this happened, how has public opinion fermented? In what way? To enter our topic today, Java design pattern -- template method pattern.
What is the template method pattern
Define the skeleton of an algorithm in an operation,deferring some steps to subclasses.
Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
Template Method Pattern: define the framework of algorithm in an operation, and delay some steps to subclass. The template method allows subclasses to redefine some steps of the algorithm without changing the structure of the algorithm. Template Method Pattern belongs to behavior pattern, which is mainly implemented by Java inheritance mechanism.
Template method, as the name implies, is a template. Do things according to the template. The template method encapsulates the execution steps of the method. The caller can do things in the correct order only by calling the template.
Two roles of template method pattern
-
Abstract class: defines a series of basic operations, which can be concrete or abstract. Each basic operation corresponds to a step of the algorithm, which can be redefined or implemented in its subclass. At the same time, a template method is defined in the abstract class, that is, an algorithm framework is defined, and the execution sequence of these operations is defined and combined.
-
ConcreteClass (concrete subclass): a subclass of an abstract class. It is used to implement the abstract basic operations declared in the parent class to complete the specific algorithm steps of the subclass. It can also cover the specific basic operations already implemented in the parent class.
UML diagram of template method pattern
Template method pattern code demonstration
I have a partner to ask, what is the relationship between template method mode and Morey event? There is no connection between them. I'm looking at the attitude towards this issue and the way we express our views. Let's abstract it again. Can we simply abstract the behavior of each of us to open social software, express opinions and close social software? what is it? When it comes to projects, isn't this a template approach? Everyone is expressing their opinions according to this template. The difference is that some people use Weibo, some people use Hupu, some use Twitter, some support Morey, some scold Morey and so on. Let's take a look at the code implementation.
1. Write abstract template class
package com.mazhichu.designpatterns.templatemethod;
/**
* <p class="detail">
* Function: abstract template class
* </p>
*
* @author Moore
* @ClassName Comment.
* @Version V1.0.
* @date 2019.10.16 11:53:02
*/
public abstract class Comment {
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
protected abstract void openSocialSoftware();
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
protected abstract void comment();
/**
* <p class="detail">
* Function: specific method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
protected void closeSocialSoftware(){
System.out.println("Turn off social software");
}
/**
* <p class="detail">
* Function: template method, template method. In order to prevent malicious operation, the general template method is added with the final keyword, and the subclass cannot be implemented.
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
public final void temtemplateMethod(){
openSocialSoftware();
comment();
closeSocialSoftware();
}
}
2. Preparation of specific categories
package com.mazhichu.designpatterns.templatemethod;
/**
* <p class="detail">
* Function: specific category
* </p>
*
* @author Moore
* @ClassName Zhang san.
* @Version V1.0.
* @date 2019.10.16 14:00:09
*/
public class ZhangSan extends Comment {
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
@Override
protected void openSocialSoftware() {
System.out.println("Open Weibo!");
}
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
@Override
protected void comment() {
System.out.println("The comment is: Morey must apologize, Xiao Hua must apologize! Fire Morey!");
}
}
package com.mazhichu.designpatterns.templatemethod;
/**
* <p class="detail">
* Function: specific category
* </p>
*
* @author Moore
* @ClassName Li si.
* @Version V1.0.
* @date 2019.10.16 13:59:56
*/
public class LiSi extends Comment {
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
@Override
protected void openSocialSoftware() {
System.out.println("Open Tiger flutter");
}
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
@Override
protected void comment() {
System.out.println("The comment is: Morey is stupid X,WQNMLGB");
}
}
package com.mazhichu.designpatterns.templatemethod;
/**
* <p class="detail">
* Function: specific category
* </p>
*
* @author Moore
* @ClassName James.
* @Version V1.0.
* @date 2019.10.16 13:59:01
*/
public class James extends Comment {
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
@Override
protected void openSocialSoftware() {
System.out.println("Open twitter");
}
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
@Override
protected void comment() {
System.out.println("The comment is: Xiao Hua should punish Morey!");
}
}
3. Client call
package com.mazhichu.designpatterns.templatemethod;
public class Client {
public static void main(String[] args) {
Comment zhangSan = new ZhangSan();
zhangSan.temtemplateMethod();
System.out.println("-----------------\n");
Comment lisi = new LiSi();
lisi.temtemplateMethod();
System.out.println("-----------------\n");
Comment james = new James();
james.temtemplateMethod();
}
}
To view run results:
The above is the template method pattern, which is probably the most common and simple design pattern. The parent class (abstract class) defines the algorithm and template method, and the template method specifies the algorithm execution order. The child class only needs to implement the abstract algorithm of the parent class, and can execute according to the established order of the template method to get different results, which greatly simplifies the complexity of the child class.
Hook Method
The reason why we take this out alone is that it is optional to execute some methods in template methods. That is to say, not all algorithms in templates need to be executed, which can be determined by subclasses. This is what we call "hook method".
Hook method is a method declared in an abstract class, which is generally empty or has a default value. A subclass can override the hook to determine whether a certain step of an algorithm step needs to be executed. This is a reverse control.
Let's change the abstract class and add the hook method.
1. Re abstract classes and add hook methods
package com.mazhichu.designpatterns.templatemethod;
/**
* <p class="detail">
* Function: abstract template class
* </p>
*
* @author Moore
* @ClassName Comment.
* @Version V1.0.
* @date 2019.10.16 11:53:02
*/
public abstract class Comment {
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
protected abstract void openSocialSoftware();
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
protected abstract void comment();
/**
* <p class="detail">
* Function: specific method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
protected void closeSocialSoftware(){
System.out.println("Turn off social software");
}
/**
* <p class="detail">
* Function: template method. In order to prevent malicious operation, the general template method is added with the final keyword, and the subclass cannot be implemented.
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
public final void temtemplateMethod(){
openSocialSoftware();
if(isLogin()){
comment();
}else {
System.out.println("You are not logged in. You can't comment. You can only watch others scold Morey.");
}
closeSocialSoftware();
}
/**
* Hook method: it can be an abstract method, an empty implementation or a default implementation. Subclasses can be overridden to determine whether template methods execute certain algorithms.
* @return
*/
protected boolean isLogin(){
System.out.println("Sign in to comment---");
return true;
}
}
2. Write a subclass covering hook method
package com.mazhichu.designpatterns.templatemethod;
public class LaoBao extends Comment {
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
@Override
protected void openSocialSoftware() {
System.out.println("Open to know");
}
/**
* <p class="detail">
* Function: basic abstract method
* </p>
*
* @author Moore
* @date 2019.10.16 11:53:02
*/
@Override
protected void comment() {
System.out.println("Not only do I want to scold Morey Xiao Hua, but I also want to greet trump.");
}
@Override
protected boolean isLogin() {
return false;
}
}
3. Client call
package com.mazhichu.designpatterns.templatemethod;
public class Client {
public static void main(String[] args) {
Comment zhangSan = new ZhangSan();
zhangSan.temtemplateMethod();
System.out.println("-----------------\n");
Comment lisi = new LiSi();
lisi.temtemplateMethod();
System.out.println("-----------------\n");
Comment james = new James();
james.temtemplateMethod();
System.out.println("-----------------\n");
Comment laobao = new LaoBao();
laobao.temtemplateMethod();
}
}
4. View the operation results:
The result shows that after adding the hook method, we can reverse control whether some algorithms in the template method in the parent class are to be executed, which also increases the flexibility of the template method.
summary
Advantages of template method pattern
-
Good encapsulation and expansibility. Encapsulate the public behavior in the parent class, realize the concrete behavior logic through the child class, expand the basic method by the child class, compound the single responsibility principle and the opening and closing principle.
-
To improve the reusability of code, template method pattern is a kind of code reusing technology, which is particularly important in class library design.
-
Reverse control, which determines whether a specific step needs to be executed by covering the hook method of the parent class with the subclass.
Disadvantages of template method pattern
-
Template methods use inheritance to reuse code. If you want to add an abstract method to an abstract class, each subclass needs to modify the code.
-
Each different implementation needs to be implemented by a subclass, which leads to the increase of the number of classes and the system becomes huge.
Template method application scenario
-
There are common methods in multiple subclasses, and the logic is the same, which can be centralized in the common parent class to prevent code duplication.
-
For some important and complex algorithms, the invariant part of the algorithm can be designed as template method, and the variable part can be implemented by subclass.
-
It is necessary to control whether an algorithm in the parent class is executed by subclass, and implement reverse control by hook method.
Knowledge points, take notes
-
In order to prevent malicious operation, the final keyword is usually added to the template method to prevent the subclass from changing the algorithm execution order in the template method.
-
Policy pattern and template method are both used to encapsulate algorithm. The former uses combination and delegation model, while the latter is inheritance.
Off the coast
The above is the explanation of template method pattern. In fact, it is very simple, which is our common encapsulation and inheritance. What I want to say here is that in fact, the design mode is not so boring and complicated. We usually pay more attention to the daily trivia in our life, think more, and the knowledge comes from the observation and summary of life. The design mode is also in every bit of our life. Finally, Hong Kong belongs to China. No country, organization, force or individual has the right to interfere in our internal affairs and the integrity of our territorial sovereignty. I hope Hong Kong will soon settle down and talk about other things.
I can't guarantee that all the articles I write are correct, but I can guarantee that all the articles I write are my own time and heart, all the code examples are original, all the understandings are only my personal understandings, and can't represent the official authority, so please read with a critical eye and selective identification, thank you!
If you think this article is useful, please recommend it to the people around you or peers to pay attention to the "beginning of code" public number, let's move forward together, thank you!
If you find any problem in the article or bug in the code, please leave a message, please comment and correct at any time, thank you!
In order to thank you for your attention and love, at the beginning of the code, we quietly send a batch of dry goods to the small partners who are looking for jobs, and send "interview" keywords in the background, so that we can get a random interview information. I wish all the small partners a better future!
In addition, the background reply "design mode", you can get the source address of design mode.