-
Notifications
You must be signed in to change notification settings - Fork 0
/
python.py
63 lines (42 loc) · 1.57 KB
/
python.py
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
# Visitor: Permite definir nuevas operaciones sin cambiar las clases de los elementos.
class Visitor(ABC):
@abstractmethod
def visit_concrete_element_a(self, element):
pass
@abstractmethod
def visit_concrete_element_b(self, element):
pass
class ConcreteVisitor1(Visitor):
def visit_concrete_element_a(self, element):
print(f"ConcreteVisitor1: {element.operation_a()}")
def visit_concrete_element_b(self, element):
print(f"ConcreteVisitor1: {element.operation_b()}")
class ConcreteVisitor2(Visitor):
def visit_concrete_element_a(self, element):
print(f"ConcreteVisitor2: {element.operation_a()}")
def visit_concrete_element_b(self, element):
print(f"ConcreteVisitor2: {element.operation_b()}")
class Element(ABC):
@abstractmethod
def accept(self, visitor: Visitor):
pass
class ConcreteElementA(Element):
def accept(self, visitor: Visitor):
visitor.visit_concrete_element_a(self)
def operation_a(self) -> str:
return "ConcreteElementA"
class ConcreteElementB(Element):
def accept(self, visitor: Visitor):
visitor.visit_concrete_element_b(self)
def operation_b(self) -> str:
return "ConcreteElementB"
elements = [ConcreteElementA(), ConcreteElementB()]
visitor1 = ConcreteVisitor1()
visitor2 = ConcreteVisitor2()
for element in elements:
element.accept(visitor1)
element.accept(visitor2)
# ConcreteVisitor1: ConcreteElementA
# ConcreteVisitor1: ConcreteElementB
# ConcreteVisitor2: ConcreteElementA
# ConcreteVisitor2: ConcreteElementB