设计模式(22)--模板方法模式

来源:互联网 发布:数据库的数据类型 编辑:程序博客网 时间:2024/06/09 16:12

模板方法,即通过父类定义的模板来执行算法或方法。而这个模板,被称作模板方法,这也是名字的由来。

举个例子,本人懒(懒人创造世界敲打),还用上一个策略模式的例子,给他稍作修改:

小明   走路(骑自行车或坐公交车) 去上学。这时候,可以定义三个方法,一,getPerson(),不一定是小明,也可能是其他人,howToGetToSchool()方法,选择哪种方式上学,where()方法,不一定去上学,可能去云南大理。所以可以定义一个模板方法,如下:

public void templateMethod(){

getPerson();

howToGetToSchool();

where();

}

以上就是该模板方法简单表示,也就是定义了一个执行顺序,而我们可以通过子类覆盖父类抽象类,从而使得这个”算法框架“可以有不同的执行结果,注意,框架是定下来的,某些特定步骤通过继承却可以重新定义。

该模式基于继承,类之间的关系,so,他是一种类行为模式。

模板方法模式UML类图:


类图很简单,就个继承关系

示例代码:

定义模板方法的模板类:


/***** * 抽象模板类,定义了算法方法执行顺序 * @author wjw * */public abstract class Template {private boolean isHealthy;public Template(boolean isHealthy){this.isHealthy = isHealthy;}/**** * 模板方法,定义方法顺序 * @return */public void tempLateMethod(){if(!isHealthy){//如果用钩子方法探测到身体不健康,不执行后面方法System.out.println("病去如山倒,哪也去不了!");}this.getPerson();this.howToGetToSchool();  this.goWhere();}public  void getPerson(){System.out.print("孔二狗");};public abstract void howToGetToSchool();public abstract void goWhere();//钩子方法public boolean isHealthy(){return isHealthy;}}

抽象模板类的子类:

public class School extends Template{public School(boolean isHealthy) {super(isHealthy);// TODO Auto-generated constructor stub}@Overridepublic void howToGetToSchool() {// TODO Auto-generated method stubSystem.out.print("背着背包步行");}@Overridepublic void goWhere() {// TODO Auto-generated method stubSystem.out.println("去四川!");}}
public class YunNan extends Template{public YunNan(boolean isHealthy) {super(isHealthy);// TODO Auto-generated constructor stub}@Overridepublic void howToGetToSchool() {// TODO Auto-generated method stubSystem.out.print("骑着自行车");}@Overridepublic void goWhere() {// TODO Auto-generated method stubSystem.out.println("去西藏!");}}





Main类:

public class Main {public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException {Class tempLateClazz = Class.forName(ReadProperties.readProperties("template_name"));Constructor templateConstructor = tempLateClazz.getConstructor(boolean.class);Template template= (Template)templateConstructor.newInstance(true);//以上通过反射new具体模板方法template.tempLateMethod();}}


运行结果:

孔二狗骑着自行车去西藏!


说明:不同的具体类执行结果不同,但都是who(谁) how(怎样) where(哪里)模式,因为按照别的循序执行方法系统就不正常了,映射到系统中就是通过一个模板方法定义一个算法框架,这个”算法框架“怎么讲?就是方法执行顺序(大框架)已经定下来了,具体方法执行那些代码留给你自己做主。


如有错误,欢迎指正

end


原创粉丝点击