在 TypeScript 继承代码中,模板模式比较常用。
定义
一个抽象类,公开定义它的方法和模板,由子类按需重写方法实现。
实现
思路:
- 抽象类实现模版方法;
- 子类实现继承,按需修改;
例子:
// 抽象类
abstract class Game {
public abstract init (): any
public abstract startPlay (): any
public abstract endPlay (): any
// 模板
public play (): any {
// 初始化
this.init()
// 开始游戏
this.startPlay()
// 结束游戏
this.endPlay()
}
}
class FootBall extends Game {
public init () {
console.log('Football Game Initialized! Start playing.')
}
public startPlay () {
console.log('Football Game Start!')
}
public endPlay () {
console.log('Football Game End!')
}
}
class BasketBall extends Game {
public init () {
console.log('BasketBall Game Initialized! Start playing.')
}
public startPlay () {
console.log('BasketBall Game Start!')
}
public endPlay () {
console.log('BasketBall Game End!')
}
}
const basketBall = new BasketBall()
basketBall.play()
console.log('==========')
const footBall = new FootBall()
footBall.play()
使用场景
- 有多个子类共有的方法,且逻辑相同;
- 重要的、复杂的方法,可以考虑作为模板方法。
优缺点
优点:
- 封装不变部分,扩展可变部分;
- 提取公共代码,便于维护;
- 行为由父类控制,子类实现。
缺点:
- 每一个不同的实现都需要一个子类来实现,导致类的个数增加,使得系统更加庞大。