模板方法模式特点:
1、模板方法模式通过把不变的行为搬移到超类,去除子类中重复的代码体现优势;提供一个很好的代码复用平台;
2、当不变的行为与可变的行为混杂在子类中的时候,不变的行为就会在子类中重复的出现,通过模板方法模式将这些不变的行为搬移到单一的地方,摆脱子类复杂的的不变行为的纠缠 ;
package caosc.javaModel.Template;
public abstract class Template {
public abstract void operation1();
public abstract void operation2();
public void templateMethod() {
operation1();
operation2();
}
}
package caosc.javaModel.Template;
public class TemplateChildA extends Template {
@Override
public void operation1() {
// TODO Auto-generated method stub
System.out.println("Chlid A operation1");
}
@Override
public void operation2() {
// TODO Auto-generated method stub
System.out.println("Chlid A operation2");
}
}
package caosc.javaModel.Template;
public class TemplateChildB extends Template {
@Override
public void operation1() {
// TODO Auto-generated method stub
System.out.println("Chlid B operation1");
}
@Override
public void operation2() {
// TODO Auto-generated method stub
System.out.println("Chlid B operation2");
}
}
package caosc.javaModel.Template;
public class TemplateTest {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Template tpA = new TemplateChildA();
Template tpB = new TemplateChildB();
tpA.templateMethod();
tpB.templateMethod();
}
}