1.定义
定义了一个算法的骨架,并允许子类为一个或多个步骤提供实现。
2.优点
提高复用性和扩展性。
3.结构
包括四类方法,模版方法、具体方法、钩子方法和抽象方法。
public abstract class TemplatePattern {
//模版方法
public void templateMethod(){
concreteMethod();
hookMethod();
abstractMethod();
}
//具体方法,模版方法里确定不变的逻辑
public void concreteMethod(){
}
//钩子方法,子类可以根据实际情况实现的方法
protected void hookMethod(){
}
//抽象方法,必须让子类实现的方法
public abstract void abstractMethod();
}
4.代码示例
public abstract class KTVRoom {
public void procedure() {
open();
orderSong();
orderExtra();
pay();
}
public void open() {
System.out.println("开启设备");
}
public abstract void orderSong();
protected void orderExtra() {
}
public void pay() {
System.out.println("付款结账");
}
}
public class ChineseCustomer extends KTVRoom {
public void orderSong() {
System.out.println("点一首中文歌曲");
}
}
public class AmericanCustomer extends KTVRoom {
public void orderSong() {
System.out.println("点一首英文歌曲");
}
@Override
public void orderExtra() {
System.out.println("点一盘西瓜");
}
}
public class Test {
public static void main(String[] args) {
ChineseCustomer chineseCustomer = new ChineseCustomer();
chineseCustomer.procedure();
System.out.println();
AmericanCustomer americanCustomer = new AmericanCustomer();
americanCustomer.procedure();
}
}
开启设备
点一首中文歌曲
付款结账
开启设备
点一首英文歌曲
点一盘西瓜
付款结账
5.源码解析
public abstract class AbstractApplicationContext extends DefaultResourceLoader implements ConfigurableApplicationContext {
//模版方法
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//1.具体方法
prepareRefresh();
//2.抽象方法
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
prepareBeanFactory(beanFactory);
try {
//3.钩子方法
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
registerBeanPostProcessors(beanFactory);
initMessageSource();
initApplicationEventMulticaster();
onRefresh();
registerListeners();
finishBeanFactoryInitialization(beanFactory);
finishRefresh();
}catch (BeansException ex) {
//......
destroyBeans();
cancelRefresh(ex);
throw ex;
} finally {
resetCommonCaches();
}
}
}
//具体方法
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (logger.isDebugEnabled()) {
if (logger.isTraceEnabled()) {
logger.trace("Refreshing " + this);
}else {
logger.debug("Refreshing " + getDisplayName());
}
}
}
//抽象方法
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
@Override
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
//钩子方法
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
}