Featured image of post 设计模式之模版模式

设计模式之模版模式

本文阅读量

设计模式:解决通用问题的架构

模版方法

解决什么问题

解决方法中存在重复性代码的问题

引出

Student类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class Student{
  public void Process() {
    System.out.println("上早自习");
    System.out.println("早餐");
    System.out.println("上课");
    System.out.println("午休");
    System.out.println("上课");
    System.out.println("放学");
  }
}

Teacher类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
public class Teache{
  public void Process() {
    System.out.println("看着学生上早自习");
    System.out.println("早餐");
    System.out.println("上课");
    System.out.println("午休");
    System.out.println("上课");
    System.out.println("下班,为第二天备课");
  }
}

以上有大量重复代码,我们可以抽出一个抽象类来处理这些重复的代码,并对其他代码抽取成方法

怎么写

People类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public abstract class People{
  public abstract Morning();
	public final void Process(){ // 使用final修饰模版方法,避免子类进行重写
    Morning();
    System.out.println("早餐");
    System.out.println("上课");
    System.out.println("午休");
    System.out.println("上课");
  }
  public abstract Evening();
}

Student类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Student{
  @Override
  public void Monning(){
    System.out.println("上早自习");
  }
  
  @Override
  public void Evening(){
    System.out.println("放学");
  }
}

Teacher类

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
public class Student{
  @Override
  public void Monning(){
    System.out.println("看着学生上早自习");
  }
  
  @Override
  public void Evening(){
    System.out.println("下班,为第二天备课");
  }
}
  1. 模版方法时给对象直接使用的,不能被子类重写
  2. 一旦子类重写了模版方法,模版方法就失效了
使用 Hugo 构建
主题 StackJimmy 设计