1. 什么是模板模式?

模板模式是抽象父类定义了子类需要重写的相关方法。
而这些方法,仍然是通过父类方法调用的。

根据描述,“模板”的思想体现在:父类定义的接口方法。

除此之外,子类方法的调用,也是被父类控制的。

2. 应用场景

一些系统的架构或者算法骨架,由“BOSS”编写抽象方法,具体的实现,交给“小弟们”实现。

而绝对是不是用“小弟们”的方法,还是看“BOSS”的心情。

不是很恰当的比喻哈~

3. 多语言实现

3.1 ES6 实现

Animal是抽象类,DogCat分别具体实现了eat()sleep()方法。

DogCat实例可以通过live()方法调用eat()sleep()

注意CatDog实例会被自动添加live()方法。不暴露live()是为了防止live()被子类重写,保证父类的控制权

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Animal {
constructor() {
// this 指向实例
this.live = () => {
this.eat()
this.sleep()
}
}

eat() {
throw new Error('模板类方法必须被重写')
}

sleep() {
throw new Error('模板类方法必须被重写')
}
}

class Dog extends Animal {
constructor(...args) {
super(...args)
}
eat() {
console.log('狗吃粮')
}
sleep() {
console.log('狗睡觉')
}
}

class Cat extends Animal {
constructor(...args) {
super(...args)
}
eat() {
console.log('猫吃粮')
}
sleep() {
console.log('猫睡觉')
}
}

/********* 以下为测试代码 ********/

// 此时, Animal中的this指向dog
let dog = new Dog()
dog.live()

// 此时, Animal中的this指向cat
let cat = new Cat()
cat.live()

4. 参考