模板方法模式
概念:在父类中实现一个算法不变的部分,并将可变的行为留给子类来实现
抽象类体现的就是一种模板模式的设计,抽象类作为多个子类的通用模板,子类在抽象类的基础上进行扩展、改造,但子类总体上会保留抽象类的行为方式。
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。解决的问题:
- 父类提供了多个子类的通用方法
- 将不确定的部分功能暴露出去,让子类去实现
public abstract class Template {
private void begin() {
System.out.println("begin");
}
// 定义为protected就是为了给子类使用
protected abstract void code();
private void end() {
System.out.println("end");
}
private void others() {
System.out.println("others");
}
// Hook,钩子函数,提供一个默认或空的实现,子类可根据需要重写
protected boolean isHaveOthers() {
return true;
}
public final void process() {
begin();
code();
end();
if (isHaveOthers()) {
others();
}
}
}
public class SubTemplate extends Template {
@Override
public void code() {
System.out.println("这是模板方法模式");
}
@Override
protected boolean isHaveOthers() {
return false;
}
}
public class Client {
public static void main(String[] args) {
Template temp = new SubTemplate();
temp.process();
}
}

更多精彩