#1.定义
模板方法模式定义:
Define the skeleton of an algorithm in an operation,deferring some steps to subclasses.Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure.
定义一个操作中的算法的框架,而将一些步骤延迟到子类中。使得子类可以不改变一个算法的结构即可重定义该算法的某些特定步骤。
#2.代码
定义抽象模板类:
//抽象模板类
public abstract class AbstractModel {
//基本方法-由子类实现,并在模板方法中调用
protected abstract void doSomething();
//基本方法
protected abstract void doAnotherthing();
//模板方法(防止恶意操作,一般加上final,不允许复写)
public final void templateMethod() {
//模板方法里调用基本方法
this.doSomething();
this.doAnotherthing();
}
}
两个模板子类:
//模板子类1
public class TestModel1 extends AbstractModel {
@Override
protected void doSomething() {
System.out.println("TestModel1 doSomething");
}
@Override
protected void doAnotherthing() {
System.out.println("TestModel1 doAnotherthing");
}
}
//模板子类2
public class TestModel2 extends AbstractModel {
@Override
protected void doSomething() {
System.out.println("TestModel2 doSomething");
}
@Override
protected void doAnotherthing() {
System.out.println("TestModel2 doAnotherthing");
}
}
场景测试:
public static void main(String[] args) {
//创建两个子类
TestModel1 model1 = new TestModel1();
TestModel2 model2 = new TestModel2();
//直接调用模板方法
model1.templateMethod();
model2.templateMethod();
}
结果:
TestModel1 doSomething
TestModel1 doAnotherthing
TestModel2 doSomething
TestModel2 doAnotherthing
#3.模板方法模式的优缺点
优点:封装了不变的部分,可变部分子类继承可易于扩展。
缺点:
#4.模板方法模式的扩展
添加钩子函数(其实即使控制语句)
抽象模板类:
//抽象模板类
public abstract class AbstractModel {
//添加控制方法的字段
private boolean isDoAnother = true;
//基本方法-由子类实现,并在模板方法中调用
protected abstract void doSomething();
//基本方法
protected abstract void doAnotherthing();
//模板方法(防止恶意操作,一般加上final,不允许复写)
public final void templateMethod() {
//模板方法里调用基本方法
this.doSomething();
//通过子类设置的属性字段控制
if (this.isDoAnother)
this.doAnotherthing();
}
//钩子函数来约束子类是否需要执行某个方法
protected void setDoAnother(boolean doAnother) {
isDoAnother = doAnother;
}
}
测试类:
public static void main(String[] args) {
//创建两个子类
TestModel1 model1 = new TestModel1();
TestModel2 model2 = new TestModel2();
//直接调用模板方法
model1.setDoAnother(false);
model1.templateMethod();
model2.templateMethod();
}
结果:
TestModel1 doSomething
TestModel2 doSomething
TestModel2 doAnotherthing