Template Method模板方法设计模式定义一个操做中算法的骨架,将具体步骤的执行延迟到子类中实现。Java中的抽象类就是使用了模板方法设计模式。模板方法设计模式结构以下: java
以文档处理为例,Template Method设计模式简单例子以下: 算法
abstract class DocumentUtil{ public void openDocument(String name){ //判断是否可以打开文档也是模版方法 if(!canOpenDocument(name)){ return; } //工厂方法 Document doc = createDocument(); if(doc != null){ docs.addDocument(doc); //模版方法 aboutToOpenDocument(doc); doc.open(); doc.read(); } } //工厂方法 public abstract Document createDocument(); //模版方法 public abstract boolean canOpenDocument(name); public abstract void aboutToOpenDocument(); } public class MyDocumentUtil extends DocumentUtil{ //实现工厂方法 public Document createDocument(){ return new Document(); } //实现模板方法 public boolean canOpenDocument(name){ if(name != null && !name.equals(“”)){ return true; } return false; } public void aboutToOpenDocument(){ System.out.println(“This is about to open document.”); } }
不少学习设计模式的人看到上面的例子后,以为Template Method模板方法设计模式很是相似Façade门面设计模式,Template Method模板方法设计模式和Façade门面设计模式的区别以下: 设计模式
(1).Template Method模板方法设计模式能够先将一些流程和框架规定好,将这些流程和框架做为程序除了的模版。具体的细节除了留给子类去实现。 app
(2).Façade门面设计模式仅仅只定义对外操做接口,具体的实现所有交给子类。 框架
策略模式使用组合,模板方法模式使用继承。工厂方法模式是模板模式的一种变体。 学习
模板方法使得子类能够在不改变算法结构的状况下,重启定义算法中的某些步骤,模板方法有如下3种变体: spa
JDK中模板方法模式应用: 设计
java.util.Collections#sort() code
Java swing/applet#paint() 继承
Java applet/servlet#init(), destory()
XML SAX#startDocument(), startElement(),endElement, endDocument()