forked from amirbigg/python-design-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvisitor.py
More file actions
60 lines (40 loc) · 1.18 KB
/
visitor.py
File metadata and controls
60 lines (40 loc) · 1.18 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
"""
Visitor
- a behavioral design pattern that allows adding new behaviors to existing class hierarchy
without altering any existing code.
"""
import abc
class PublicVehicle(abc.ABC): # Abstract Element
def __init__(self, dest):
self.dest = dest
@abc.abstractmethod
def order_ticket(self, ordering):
pass
class Train(PublicVehicle): # Concrete Element
def order_ticket(self, ordering):
ordering.train_ticket(self)
class Bus(PublicVehicle): # Concrete Element
def order_ticket(self, ordering):
ordering.bus_ticket(self)
class Plane(PublicVehicle): # Concrete Element
def order_ticket(self, ordering):
ordering.plane_ticket(self)
class Ticket(abc.ABC): # Abstract Visitor
@abc.abstractmethod
def train_ticket(self, train):
pass
@abc.abstractmethod
def bus_ticket(self, bus):
pass
@abc.abstractmethod
def plane_ticket(self, plane):
pass
class Order(Ticket): # Concrete Visitor
def train_ticket(self, train):
print(f'This is a train ticket to {train.dest}')
def bus_ticket(self, bus):
print(f'This is a bus ticket to {bus.dest}')
def plane_ticket(self, plane):
print(f'This is a plane ticket to {plane.dest}')
o = Order()
Train('Tehran').order_ticket(o)