http://www.cnblogs.com/java-my-life/archive/2012/05/14/2495235.html
模板模式
一句话来说,就是比人将骨架设计好,你自己填充其余的东西就好了。
上文链接的这篇讲解模板模式的文章写的太好了,自己不想再重复写一遍,有不懂的地方,直接看上文链接就好。
接下来将自己的思考记录一下。
模板方法,常见的一个地方就是servlet的实现。首先在web.xml文件中配置,此外需要实现HttpServlet的抽象类。最后在子类中重写doGet()和doPost()方法就可以正常跑程序了。当时很困惑里面的原因,今天看到模板设计模式并翻了Servlet的源码,才明白其中的道理。再简单不过。惭愧。自己要多动手,实践。实践出真知。
另一处看到模板方法的例子是在Spring源码中。
1 protected void doRegisterBeanDefinitions(Element root) { 2 String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE); 3 if (StringUtils.hasText(profileSpec)) { 4 Assert.state(this.environment != null, "Environment must be set for evaluating profiles"); 5 String[] specifiedProfiles = StringUtils.tokenizeToStringArray( 6 profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS); 7 if (!this.environment.acceptsProfiles(specifiedProfiles)) { 8 return; 9 } 10 } 11 12 // Any nested <beans> elements will cause recursion in this method. In 13 // order to propagate and preserve <beans> default-* attributes correctly, 14 // keep track of the current (parent) delegate, which may be null. Create 15 // the new (child) delegate with a reference to the parent for fallback purposes, 16 // then ultimately reset this.delegate back to its original (parent) reference. 17 // this behavior emulates a stack of delegates without actually necessitating one. 18 BeanDefinitionParserDelegate parent = this.delegate; 19 this.delegate = createDelegate(this.readerContext, root, parent); 20 21 preProcessXml(root); 22 parseBeanDefinitions(root, this.delegate); 23 postProcessXml(root); 24 25 this.delegate = parent; 26 }
在21行和23行的地方,应该是处理XML文件的前后处理,但是进到方法里面才发现,空空如也。
1 /** 2 * Allow the XML to be extensible by processing any custom element types first, 3 * before we start to process the bean definitions. This method is a natural 4 * extension point for any other custom pre-processing of the XML. 5 * <p>The default implementation is empty. Subclasses can override this method to 6 * convert custom elements into standard Spring bean definitions, for example. 7 * Implementors have access to the parser‘s bean definition reader and the 8 * underlying XML resource, through the corresponding accessors. 9 * @see #getReaderContext() 10 */ 11 protected void preProcessXml(Element root) { 12 }
在源码preProcessXml()的上方注释中看到,可以自定义子类,重写这个方法,这就达到了类的扩展的目的。