模板方法模式:定义一个操作中算法的骨架,将一些步骤延迟到子类中实现。模板方法模式是基于”继承“的;通过一个父类调用其子类的操作,通过对子类的具体实现扩展不同的行为,实现了反向控制 & 符合“开闭原则”。
举例:
package template;
public abstract class Game {
abstract void initialize();
abstract void startPlay();
abstract void endPlay();
public final void play() {
initialize();
startPlay();
endPlay();
}
}
package template;
public class Football extends Game {
public void initialize() {
System.out.println("⚽初始化");
}
public void startPlay() {
System.out.println("⚽开始");
}
public void endPlay() {
System.out.println("⚽结束");
}
}
package template;
public class Basketball extends Game{
public void initialize() {
System.out.println("?初始化");
}
public void startPlay() {
System.out.println("?开始");
}
public void endPlay() {
System.out.println("?结束");
}
}
package template;
public class Client {
public static void main(String[] args) {
Game fb = new Football();
Game bb = new Basketball();
fb.play();
bb.play();
}
}