8-Template method
An applicationframework allows you to inherit from a class or set of classes and create a newapplication, reusing most of the code in the existing classes and overridingone or more methods in order to customize the application to your needs. Afundamental concept in the application framework is the Template Methodwhich is typically hidden beneath the covers and drives the application bycalling the various methods in the base class (some of which you haveoverridden in order to create the application).
//: templatemethod:TemplateMethod.java
// Simple demonstration of TemplateMethod.
package templatemethod;
import junit.framework.*;
?
abstract class ApplicationFramework {
? public ApplicationFramework() {
??? templateMethod(); // Dangerous!
? }
? abstract void customize1();
? abstract void customize2();
? final void templateMethod() {
??? for(int i = 0; i < 5; i++) {
????? customize1();
????? customize2();
??? }
? }
}
?
// Create a new "application":
class MyApp extends ApplicationFramework{
? void customize1() {
??? System.out.print("Hello ");
? }
? void customize2() {
???System.out.println("World!");
? }
}
?
public class TemplateMethod extendsTestCase ?{
? MyApp app = new MyApp();
? public void test() {
??? // The MyApp constructor does all thework.
??? // This just makes sure it willcomplete
??? // without throwing an exception.
? }
? public static void main(String args[]){
??? junit.textui.TestRunner.run(TemplateMethod.class);
? }
} ///:~
The base-classconstructor is responsible for performing the necessary initialization and thenstarting the “engine” (the template method) that runs the application (in a GUIapplication, this “engine” would be the main event loop). The client programmersimply provides definitions for customize1(?) and customize2(?)and the “application” is ready to run.
?
//上面的例子比较简单,很容易就能看明白,在时间当中可就没有那么容易。主要是体现在抽象函数的复杂性。我接触过的和能想到的实际应用就是:
<1>Servlet开发,只用你extends HttpServlet ,覆盖其中的doGet(),doPost()方法就好了。具体servlet的调用是由web服务器来完成的(服务器应用Template Method 模式隐藏了具体的数据连接、传输的过程,比如Socket连接等,这个只要稍微看看Tomcate的初始源码就可以了解了),只要你在自己实现函数中,将业务处理部分添加,然后,将实现类在web.xml中配置好就OK了,这个是一个很典型的应用;
<2>此外就是JDBC中,jdbcTemplate开源应用中,应用的Template Method模式,就连接数据库,或者是启用数据源的应用部分封装在模板类中,而将具体的查询类接口通过DAO设计模式,暴露出来,同样,这个应用也是很典型的!
?