设计模式之模板方法
模板方法定义
模板方法模式定义了一个操作中的算法骨架,并将一些步骤延迟到子类中实现。这样,子类在不改变算法结构的情况下,可以重新定义算法的某些特定步骤
模板方法模式非常简单易于理解
- 定义模板
public abstract class TemplateMethod {
public void calculate() {
System.out.println("step1");
System.out.println("step2");
System.out.println("step3");
handle();
}
protected abstract void handle();
}
- 子类特定算法步骤
public class SubClassCalculate extends TemplateMethod{
@Override
protected void handle() {
System.out.println("subClass step4");
}
}
模板方法模式和工厂方法模式(点这里)实现比较类似,都是通过子类继承抽象类
- 工厂方法模式略显复杂,它有四个特定角色,其目的是将创建对象的过程延迟到子类执行;
- 模板方法则是将特定算法延迟到子类执行
模板方法优点
- 封装不变部分:将可变部分封装在抽象方法中,不变部分封装在基本方法中,使得子类可以根据需求对可变部分进行扩展,而不变部分仍然保持不变。
- 避免重复代码:抽象类中包含的基本方法可以避免子类重复实现相同的代码逻辑。
- 更好的扩展性:由于具体实现由子类来完成,因此可以方便地扩展新的功能或变更实现方式,同时不影响模板方法本身。
源码级应用场景
- Spring bean工厂,创建bean对象的模板方法
public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport implements ConfigurableBeanFactory {
//判断bean factory是否存在名字为beanName的BeanDefinition
protected abstract boolean containsBeanDefinition(String beanName);
// Spring非常核心的创建bean对象的方法,doGetBean()方法调用的
protected abstract Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException;
}
- SpringMVC处理请求的模板类及模板方法
public abstract class AbstractController extends WebContentGenerator implements Controller {
@Nullable
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
if (HttpMethod.OPTIONS.matches(request.getMethod())) {
response.setHeader("Allow", this.getAllowHeader());
return null;
} else {
this.checkRequest(request);
this.prepareResponse(response);
if (this.synchronizeOnSession) {
HttpSession session = request.getSession(false);
if (session != null) {
Object mutex = WebUtils.getSessionMutex(session);
synchronized(mutex) {
return this.handleRequestInternal(request, response);
}
}
}
return this.handleRequestInternal(request, response);
}
}
@Nullable
protected abstract ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
原文地址:https://blog.csdn.net/weixin_36279234/article/details/136983048
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!