模板方法模式,父类封装流程,子类具体实现

12/30/2022 设计模式

# 模板方法模式,父类封装流程,子类具体实现

我们知道,冲制饮料一般有以下步骤: (1)把水煮沸 (2)用沸水冲泡饮料 (3)把饮料倒进杯子 (4)加调料 示例代码:

    // 父类:实现泡制饮料的子类功能的流程,本次功能有4个流程,如下:
    var Beverage = function () {}
    // 然后,我们梳理冲制饮料的流程
    Beverage.prototype.boilWater = function () {
        console.log('公共流程:把水煮沸')
    }
    Beverage.prototype.brew = function () {
        throw new Error( '子类必须重写 brew 方法' );
    }
    Beverage.prototype.pourInCup = function () {
        throw new Error( '子类必须重写 pourInCup 方法' );
    }
    Beverage.prototype.addCondiments = function () {
        throw new Error( '子类必须重写 addCondiments 方法' );
    } 
    // 冲制饮料
    Beverage.prototype.init = function () {
        this.boilWater();
        this.brew();
        this.pourInCup();
        this.addCondiments();
    }
    // 子类:具体实现泡制一杯茶的的流程
    var Tea = function () {}
    Tea.prototype = new Beverage();
    Tea.prototype.brew = function () {
        console.log('用水泡茶');
    }
    Tea.prototype.pourInCup = function () {
        console.log('将茶倒进杯子');
    }
    Tea.prototype.addCondiments = function () {
        console.log('加冰糖');
    }
    var tea = new Tea();
    tea.init()
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

参考 (opens new window)

Last Updated: 12/30/2022, 2:33:12 PM