-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTemplateMethodPattern.js
More file actions
71 lines (60 loc) · 1.67 KB
/
Copy pathTemplateMethodPattern.js
File metadata and controls
71 lines (60 loc) · 1.67 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
"use strict";
/**
* Template Method Pattern - define a set of algorithms while allowing its subclasses
* to override some methods in order to work with a particular object.
*
* Example - The making of caffeine beverages such as tea and coffee have similar
* processes except a few that might need a little tweak. These processes can follow
* a template to reduce code duplication
*
*/
function forceRequiredMethods(_class, methods) {
for (let eachMethod of methods) {
if(_class[eachMethod] === undefined || typeof _class[eachMethod] !== "function") {
throw new TypeError(eachMethod + " is required and has to be overriden.");
}
}
}
class CaffeineBeverage {
constructor() {
let _class = this;
forceRequiredMethods(_class, ["brew", "addCondiments"])
}
boilWater() {
console.log("Boiling Water")
}
pourIntoCup() {
console.log("Pouring boiled water into the cup");
}
decorate() {
console.log("This is an optional method, which is called a hook method. The subclasses can choose whether to call this method or not");
}
}
class Tea extends CaffeineBeverage {
brew() {
console.log("Steeping in a tea bag into the cup");
}
addCondiments() {
console.log("Adding lemon into the cup");
}
}
class Coffee extends CaffeineBeverage {
brew() {
console.log("Brewing coffee grinds in the cup");
}
addCondiments() {
console.log("Adding sugar and milk into the cup");
}
}
console.log("----- Tea -----");
var tea = new Tea();
tea.boilWater();
tea.brew();
tea.pourIntoCup();
tea.addCondiments();
console.log("----- Coffee -----");
var coffee = new Coffee();
coffee.boilWater();
coffee.brew();
coffee.pourIntoCup();
coffee.addCondiments();