1.模板模式介绍
- 定义一个固定的组合算法骨架,而将一些算法延迟到子类实现
- 解决:多个类中的某个方法,逻辑相同,只有部分实现不一样,出现了大量重复代码。
- 使用场景:有多个子类共有方法,且逻辑相同
- 特点:一般模板方法会加上final防止被恶意重写
2.代码实现之
public abstract class SoyaBeanMilk {
public final void make(){
materialSelection();
if (supportAddSeasoning())
addSeasoning();
invasion();
grind();
}
protected void materialSelection(){
System.out.println("选材....");
}
protected abstract void addSeasoning();
protected void invasion(){
System.out.println("侵泡....");
}
protected void grind(){
System.out.println("研磨....");
}
protected boolean supportAddSeasoning(){
return true;
}
}
public class RedSoyaBeanMilk extends SoyaBeanMilk{
@Override
protected void addSeasoning() {
System.out.println("添加红豆....");
}
}
- 新建纯豆浆类,无添加,重写支持添加辅料方法,返回false
public class PureSoyaBeanMilk extends SoyaBeanMilk{
@Override
protected void addSeasoning() {
}
@Override
protected boolean supportAddSeasoning() {
return false;
}
}
public class TemplateTest {
public static void main(String[] args) {
SoyaBeanMilk redSoyaBeanMilk = new RedSoyaBeanMilk();
redSoyaBeanMilk.make();
System.out.println("============================");
SoyaBeanMilk pureSoyaBeanMilk = new PureSoyaBeanMilk();
pureSoyaBeanMilk.make();
}
}
选材....
添加红豆....
侵泡....
研磨....
============================
选材....
侵泡....
研磨....