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 is structure .
定义一个操作中的算法的框架,而将一些步骤延续到子类中。使得子类可以不改变一个算法的结构即可重定义该算法中的某些特定步骤。
首先创建一个去吃饭的场景类
public abstract class EatFood{
//先去饭店
protected abstract void toRestaurant();
//吃饭
protected abstract void eat();
//打包
protected abstract void bale();
//付钱
protected abstract void pay();
//去吃饭
public final void toEat(){
this.toRestaurant();
this.eat();
if (!this.isRemaining()){
this.bale();
}
this.pay();
}
//默认吃完了
protected boolean isRemaining(){
return true;
}
}
吃饭分两种,在附近吃,没吃完要打包,在远处吃,吃不完就算了,扔了吧
public class FarEat extends EatFood{
@Override
protected void toRestaurant() {
System.out.println("去远处的餐厅");
}
@Override
protected void eat() {
System.out.println("吃饭");
}
@Override
protected void bale() {
System.out.println("没吃完,打包");
}
@Override
protected void pay() {
System.out.println("付钱");
}
}
public class NearbyEat extends EatFood{
private Boolean isOk = true;
@Override
protected void toRestaurant() {
System.out.println("去附近的餐厅");
}
@Override
protected void eat() {
System.out.println("吃饭");
}
@Override
protected void bale() {
System.out.println("没吃完,打包");
}
@Override
protected void pay() {
System.out.println("付钱");
}
@Override
protected boolean isRemaining(){
return this.isOk;
}
public void setIsOk(Boolean b){
this.isOk = b;
}
}
当然了,附近你吃完了也是不用打包的,好了,我们去吃饭了
public class Test {
public static void main(String[] args) {
FarEat farEat = new FarEat();
farEat.toEat();
NearbyEat nearbyEat = new NearbyEat();
nearbyEat.setIsOk(false);
nearbyEat.toEat();
}
}
运行如下:
去远处的餐厅
吃饭
付钱
去附近的餐厅
吃饭
没吃完,打包
付钱
模板方法定义是将公用的方法提升到父类。当然了,我们上面了实例中使用了钩子方法,实现了在子类中控制父类方法。在实际应用中比较广泛
模板方式是一个相对简单的设计模式,优点有三点:
1.封装不变,扩展可变
2.提取公共部分,便于维护
3.行为由父类控制,子类实现
使用场景是在子类有多个公用方法时候,或者换一种说法就是当你的一个代码有重复的时候可以考虑使用模板方法模式。