Implementing Visitor pattern with Python
The Visitor pattern is an object behavior pattern that can be used to separate data structures from operations on structures. Through this separation, the goal of adding new operations without modifying the original structure can be achieved.
The following is an example code of using Python to implement Visitor pattern:
python
#Define a data structure
class Element:
def accept(self, visitor):
pass
#Specific data structure A
class ConcreteElementA(Element):
def accept(self, visitor):
visitor.visit_concrete_element_a(self)
#Specific data structure B
class ConcreteElementB(Element):
def accept(self, visitor):
visitor.visit_concrete_element_b(self)
#Define visitor interface
class Visitor:
def visit_concrete_element_a(self, element_a):
pass
def visit_concrete_element_b(self, element_b):
pass
#Specific visitor implementation A
class ConcreteVisitorA(Visitor):
def visit_concrete_element_a(self, element_a):
print("Visitor A is visiting ConcreteElementA")
def visit_concrete_element_b(self, element_b):
print("Visitor A is visiting ConcreteElementB")
#Specific Visitor Implementation B
class ConcreteVisitorB(Visitor):
def visit_concrete_element_a(self, element_a):
print("Visitor B is visiting ConcreteElementA")
def visit_concrete_element_b(self, element_b):
print("Visitor B is visiting ConcreteElementB")
#Creating Data Structure Objects
element_a = ConcreteElementA()
element_b = ConcreteElementB()
#Create Visitor Object
visitor_a = ConcreteVisitorA()
visitor_b = ConcreteVisitorB()
#Enable visitors to access data structures
element_a.accept(visitor_a)
element_b.accept(visitor_a)
element_a.accept(visitor_b)
element_b.accept(visitor_b)
Running the above code yields the following output:
Visitor A is visiting ConcreteElementA
Visitor A is visiting ConcreteElementB
Visitor B is visiting ConcreteElementA
Visitor B is visiting ConcreteElementB
This indicates that using the Visitor pattern, you can add new access operations to the data structure without modifying the data structure.