-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTemplateMethodPattern.py
More file actions
56 lines (43 loc) · 1.3 KB
/
Copy pathTemplateMethodPattern.py
File metadata and controls
56 lines (43 loc) · 1.3 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
"""
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
"""
from abc import abstractmethod
class CaffeineBeverage:
def boilWater(self):
print "Boiling Water"
@abstractmethod
def brew(self):
pass
def pourIntoCup(self):
print "Pouring boiled water into the cup"
@abstractmethod
def addCondiments(self):
pass
def decorate(self):
print "This is an optional method, which is called a hook method. The subclasses can choose whether to call it or not"
class Tea(CaffeineBeverage):
def brew(self):
print "Steeping in a tea bag into the cup"
def addCondiments(self):
print "Adding lemon into the cup"
class Coffee(CaffeineBeverage):
def brew(self):
print "Brewing coffee grinds in the cup"
def addCondiments(self):
print "Adding sugar and milk into the cup"
print "----- Tea -----"
tea = Tea()
tea.boilWater()
tea.brew()
tea.pourIntoCup()
tea.addCondiments()
print "----- Coffee -----"
coffee = Coffee()
coffee.boilWater()
coffee.brew()
coffee.pourIntoCup()
coffee.addCondiments()