定义: 定义一个操作中的算法框架,而将一些步骤延迟到子类中,使得子类不改变算法的结构即可重复定义算法的某些特点步骤。
角色:
- AbstractClass抽象类,定义算法结构,还可以提供通用实现。
- ConcreteClass具体实现类,选择性的重定义算法中某些特定步骤。
解决的问题:
一些方法通用,却在每一个子类都重新写了这一方法。
优缺点:
优点:
- 封装不变部分,扩展可变部分。
- 提取公共代码,便于维护。
- 行为由父类控制,子类实现。
缺点: 每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大。
使用场景:
- 有多个子类共有的方法,且逻辑相同
- 重要的、复杂的方法,可以考虑作为模板方法。
**注意事项: **
为防止恶意操作,一般模板方法都加上 final 关键词
示例代码:
Game.java
package com.test.template;
/**
*
*/
public abstract class Game {
public abstract void initialize();
public abstract void startPlay();
public abstract void endPlay();
public final void play() {
System.out.println("turn on the game");
// 初始化游戏
initialize();
// 开始游戏
startPlay();
//结束游戏
endPlay();
System.out.println("turn off the game");
}
}
LOLGame.java
package com.test.template;
public class LOLGame extends Game {
@Override
public void initialize() {
System.out.println("initialize LOL game");
}
@Override
public void startPlay() {
System.out.println("Attack the enemy battlefield");
}
@Override
public void endPlay() {
System.out.println("Don't win, lose, quit the game");
}
}
Client.java
package com.test.template;
public class Client {
public static void main(String[] args) {
Game game = new LOLGame();
game.play();
}
}
运行结果:
> Task :template:Client.main()
turn on the game
initialize LOL game
Attack the enemy battlefield
Don't win, lose, quit the game
turn off the game