当前位置:网站首页>Template method pattern
Template method pattern
2022-06-29 04:23:00 【Change with affection】
Introduction to template methods and patterns
- Template method pattern (Template Method Pattern), Also called template mode (Template Pattern), In an abstract class, the template that defines the method to execute it is exposed . Its subclass can override method implementation as needed , But the call will take place in the way defined in the abstract class .
- In short , The template method pattern defines the skeleton of an algorithm in operation , Instead, defer some steps to subclasses , So that the subclass can not change the structure of an algorithm , You can redefine some specific steps of the algorithm
- Template method pattern belongs to behavior pattern .
Case a : Template method pattern
The procedure for preparing soybean milk is as follows :
- Process and material selection for making soybean milk -- Add ingredients – soak – Break it in the soymilk machine
- By adding different ingredients , You can make soymilk with different flavors
- Material selection 、 Soaking and smashing in a soymilk machine are the same for every flavor of soymilk

// abstract class , It means soybean milk
public abstract class SoyaMilk {
// Template method , make , Template method can be made into final , Don't let subclasses cover .
final void make() {
select();
addCondiments();
soak();
beat();
}
// Selected materials
void select() {
System.out.println(" First step : Choose good fresh soybeans "); }
// Add different ingredients , Abstract method , Subclass specific implementation
abstract void addCondiments();
// soak
void soak() {
System.out.println(" The third step , Soybeans and ingredients begin to soak , need 3 Hours "); }
void beat() {
System.out.println(" Step four : Put the soybeans and ingredients into the soymilk machine to break them "); }
}
public class RedBeanSoyaMilk extends SoyaMilk {
@Override
void addCondiments() {
System.out.println(" Add the best red beans ");
}
}
public class PeanutSoyaMilk extends SoyaMilk {
@Override
void addCondiments() {
System.out.println(" Add good peanuts ");
}
}
public class Client {
public static void main(String[] args) {
System.out.println("---- Make red bean milk ----");
SoyaMilk redBeanSoyaMilk = new RedBeanSoyaMilk();
redBeanSoyaMilk.make();
System.out.println("---- Making peanuts and soymilk ----");
SoyaMilk peanutSoyaMilk = new PeanutSoyaMilk();
peanutSoyaMilk.make();
}
}
Case 2 : Improved hook method of template method pattern
- In the parent class of the template method pattern , We can define a method , It does nothing by default , Subclasses can override it as appropriate , This method is called “ hook ”.
- such as , We also want to make pure soymilk , No ingredients added , Use the hook method to transform the previous template method

// abstract class , It means soybean milk
public abstract class SoyaMilk {
// Template method , make , Template method can be made into final , Don't let subclasses cover .
final void make() {
select();
if(customerWantCondiments()) {
addCondiments();
}
soak();
beat();
}
// Selected materials
void select() {
System.out.println(" First step : Choose good fresh soybeans "); }
// Add different ingredients , Abstract method , Subclass specific implementation
abstract void addCondiments();
// soak
void soak() {
System.out.println(" The third step , Soybeans and ingredients begin to soak , need 3 Hours "); }
void beat() {
System.out.println(" Step four : Put the soybeans and ingredients into the soymilk machine to break them "); }
// Hook method , Decide if ingredients need to be added
boolean customerWantCondiments() {
return true; }
}
public class PureSoyaMilk extends SoyaMilk{
@Override
void addCondiments() {
// Empty implementation
}
@Override
boolean customerWantCondiments() {
return false;
}
}
public class Client {
public static void main(String[] args) {
System.out.println("---- Make pure soybean milk ----");
SoyaMilk pureSoyaMilk = new PureSoyaMilk();
pureSoyaMilk.make();
}
}
The template method pattern is in Spring Source code analysis of framework application
Spring IOC The template method pattern used in container initialization
public interface ConfigurableApplicationContext extends ApplicationContext, Lifecycle, Closeable {
void refresh();
}
postProcessBeanFactory It's the hook method
onRrfresh Also a hook method .
They are in the template method refresh By using
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
beanPostProcess.end();
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var10) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var10);
}
this.destroyBeans();
this.cancelRefresh(var10);
throw var10;
} finally {
this.resetCommonCaches();
contextRefresh.end();
}
}
}
}
summary
- The basic idea is : Algorithms only exist in one place , That is, in the parent class , Easy to modify . When you need to modify the algorithm , Just modify the template method of the parent class or some steps that have been implemented , Subclasses inherit these changes
- Achieve maximum code reuse . The template method of the parent class and some implemented steps will be inherited by the subclass and used directly .
- It unifies the algorithm , It also provides a lot of flexibility . The template method of the parent class ensures that the structure of the algorithm remains unchanged , At the same time, the implementation of some steps is provided by subclasses .
- The shortcomings of this model : Each different implementation requires a Subclass implementation , Causes the number of classes to increase , Make the system bigger
- General template methods add final keyword , Prevent subclasses from overriding template methods .
- Template method pattern usage scenarios : When a process is to be completed , The process involves a series of steps , This series of steps is basically the same , But its individual steps may be different when implemented , The template method pattern is usually considered to handle
边栏推荐
- Idea modifying JVM memory
- Error accessing database
- PostgreSQL has a cross database references are not implemented bug
- Binary tree serialization and deserialization (leetcode (difficult))
- 树莓派用VNC Viewer方式远程连接
- 【HackTheBox】dancing(SMB)
- On June 27, 2022, I have the right to choose the journey of the summer vacation.
- JDBC man Han building code
- 1019 digital black hole
- Five thousand years of China
猜你喜欢

Ask a simple question about SQL

How to create robots Txt file?

赚钱的5个层次,你在哪一层?

How to use the select statement of MySQL

Analysis of moudo Network Library

女程序员晒出5月的工资条:工资是高,但是真累,网友评论炸锅了

yolox出现 RuntimeError: DataLoader worker (pid(s) 17724, 1364, 18928) exited unexpectedly

从零到一,教你搭建「以文搜图」搜索服务(一)

Anaconda自带的Spyder编辑器启动报错问题

Rapid development project -vscode plug-in
随机推荐
MySQL column to row conversion without Union
Hot renewal process
From zero to one, I will teach you to build a "search by text and map" search service (I)
Wi-Fi 7 来啦,它到底有多强?
Emotional changes need to be controlled
Implementation of thread pool based on variable parameter template
请问大佬,Oracle CDC报错 Call snapshotState on closed sou
Ansible最佳实践之Playbook不同上下文提权Demo
Multi machine LAN office artifact rustdesk use push!!!
NotImplementedError: Could not run torchvision::nms
[wc2021] Fibonacci - number theory, Fibonacci sequence
1018 hammer scissors cloth
The virtual machine MySQL cannot be connected to the local computer
人民银行印发《关于支持外贸新业态跨境人民币结算的通知》
Is the sink usually the JDBC insert update delete?
SQL two columns become multi row filter display
The 30th day of force deduction (DP topic)
ROS URDF model is parsed into KDL tree
JDBC man Han building code
[C language] explain the thread recycling function pthread_ join