[关键字]:java,design pattern,设计模式,《Java与模式》学习,template method pattern,模板方法模式
[环境]:StarUML5.0 + JDK6
[作者]:Winty (wintys@gmail.com) http://www.blogjava.net/wintys/
[正文]:
![](http://dl.iteye.com/upload/attachment/153607/a0ea65ac-eb15-3684-ac68-30e9c82f0fd5.jpg)
package pattern.template;
/**
* 模板方法模式:Template Method Pattern
* @version 2009-6-15
* @author Winty(wintys@gmail.com)
*/
public class TemplateMethodTest{
public static void main(String[] args){
AbstractClass ac = new ConcreteClass();
ac.theTemplateMethod();
}
}
/**
* 抽象模板角色,在此定义模板方法
*/
abstract class AbstractClass{
public void theTemplateMethod(){
operation1();
operation2();
operation3();
doHookOperation();
}
protected abstract void operation1();
protected abstract void operation2();
public final void operation3(){
System.out.println("operation3");
}
public void doHookOperation(){
//空方法
}
}
/**
* 具体模板角色
*/
class ConcreteClass extends AbstractClass{
protected void operation1(){
System.out.println("operation1");
}
protected void operation2(){
System.out.println("operation2");
}
}
/**
* 模板方法模式:Template Method Pattern
* @version 2009-6-15
* @author Winty(wintys@gmail.com)
*/
public class TemplateMethodTest{
public static void main(String[] args){
AbstractClass ac = new ConcreteClass();
ac.theTemplateMethod();
}
}
/**
* 抽象模板角色,在此定义模板方法
*/
abstract class AbstractClass{
public void theTemplateMethod(){
operation1();
operation2();
operation3();
doHookOperation();
}
protected abstract void operation1();
protected abstract void operation2();
public final void operation3(){
System.out.println("operation3");
}
public void doHookOperation(){
//空方法
}
}
/**
* 具体模板角色
*/
class ConcreteClass extends AbstractClass{
protected void operation1(){
System.out.println("operation1");
}
protected void operation2(){
System.out.println("operation2");
}
}