意图
定义一个操作中的算法骨架,而将一些操作延迟到子类中。TemplateMethod使得子类可以不改变一个算法的结构即可重新定义该算法的某些特定步骤。
示例代码
abstract class SuperHero{
public void FrightCrime(){
this.Name();
this.MainWeapon();
this.SubWeapon();
}
protected abstract void Name();
protected abstract void MainWeapon();
protected abstract void SubWeapon();
}
class CaptainAmerican extends SuperHero{
@Override
public void Name() {
System.out.println("Captain American");
}
@Override
public void MainWeapon() {
System.out.println("A Sheild which is nearly indestructible ");
}
@Override
public void SubWeapon() {
System.out.println("kicks and fists");
}
}
class IronMan extends SuperHero{
@Override
public void Name() {
System.out.println("Iron Man");
}
@Override
public void MainWeapon() {
System.out.println("Chess Canon");
}
@Override
public void SubWeapon() {
System.out.println("Plam Canon");
}
}
public class Client {
public static void main(String[] args) {
SuperHero captainAmerican=new CaptainAmerican();
SuperHero ironman=new IronMan();
captainAmerican.FrightCrime();
ironman.FrightCrime();
}
}
输出结果
Captain American
A Sheild which is nearly indestructible
kicks and fists
Iron Man
Chess Canon
Plam Canon