Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. The template method lets subclasses redefine certain steps of an algorithm without changing the algorithm’s structure.
定义一个算法操作的骨架(模板方法),延迟某些步骤由具体子类来实现,而不改变整个操作的算法结构。
模板类
/**
* 模板类
*/
public abstract class AbstractEngineering {
/**
* 模板方法
*/
public void papers() {
// Common papers:
math();
softSkills();
// Specialized Paper:
specialPaper();
}
private void math() {
System.out.println("Mathematics");
}
private void softSkills() {
System.out.println("SoftSkills");
}
// 抽象方法由实现类提供
public abstract void specialPaper();
}
定义模板方法,模板方法定义整个算法结构
实现类
public class ComputerScience extends AbstractEngineering {
@Override
public void specialPaper() {
System.out.println("Object Oriented Programming");
}
}
public class Electronics extends AbstractEngineering {
@Override
public void specialPaper() {
System.out.println("Digital Logic and Circuit Theory");
}
}
执行
public class Test {
public static void main(String[] args) {
AbstractEngineering cs = new ComputerScience();
cs.papers();
AbstractEngineering es = new Electronics();
es.papers();
}
}
网友评论