-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathVisitor.py
More file actions
99 lines (72 loc) · 2.1 KB
/
Visitor.py
File metadata and controls
99 lines (72 loc) · 2.1 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# @Time : 2022/08/31 10:16:59
# @Author : Gary
# @Email : None
class Medicine:
# 抽象对象
name = ""
price = 0.0
def __init__(self, name, price):
self.name = name
self.price = price
def getName(self):
return self.name
def setName(self, name):
self.name = name
def getPrice(self):
return self.price
def setPrice(self, price):
self.price = price
def accept(self, visitor):
pass
class Antibiotic(Medicine):
# 具体对象
def accept(self, visitor):
visitor.visit(self)
class Coldrex(Medicine):
# 具体对象
def accept(self, visitor):
visitor.visit(self)
class Visitor:
# 抽象访问者
name = ""
def setName(self, name):
self.name = name
def visit(self, medicine):
pass
class Charger(Visitor):
# 具体访问者
def visit(self, medicine):
print("CHARGE: %s lists the Medicine %s. Price:%s " %
(self.name, medicine.getName(), medicine.getPrice()))
class Pharmacy(Visitor):
# 具体访问者
def visit(self, medicine):
print("PHARMACY:%s offers the Medicine %s. Price:%s" %
(self.name, medicine.getName(), medicine.getPrice()))
class ObjectStructure:
# 抽象对象结构
pass
class Prescription(ObjectStructure):
# 具体对象结构
medicines = []
def addMedicine(self, medicine):
self.medicines.append(medicine)
def rmvMedicine(self, medicine):
self.medicines.append(medicine)
def visit(self, visitor):
for medc in self.medicines:
medc.accept(visitor)
if __name__ == "__main__":
yinqiao_pill = Coldrex("Yinqiao Pill", 2.0)
penicillin = Antibiotic("Penicillin", 3.0)
doctor_prsrp = Prescription()
doctor_prsrp.addMedicine(yinqiao_pill)
doctor_prsrp.addMedicine(penicillin)
charger = Charger()
charger.setName("Doctor Strange")
pharmacy = Pharmacy()
pharmacy.setName("Doctor Wei")
doctor_prsrp.visit(charger)
doctor_prsrp.visit(pharmacy)