What is visitor pattern?
1. It encapsulates an operation executed on an object hierarchy in an object. That says, it allows to add methods to classes of different types without much altering to those classes.
2. Enables to define new operations without changing the object hierarchy.
a. Operations shall be performed on object hierarchy
b. The operations change frequently but object hierarchy is stable.
Basic UML Class Diagram:
· Defines the visit operation on the object structure
· Implements the visit operation for each type of object
· Defines the accept operation which takes visitor as an argument
· Implements accept operations
The Visitor pattern has two types of hierarchies. The object hierarchy (Visitable elements) and the operation hierarchy (TaxVisitor). The object hierarchy is pretty stable, but operation hierarchy may support different operations on same object hierarchy. In our case Visitor and Visitable acts as interfaces. What does it mean? It means Liquor, Tobacco and Necessity must implement accept member function. Similarly, TaxVisitor must implement overloads of visit function for each object type.
Operation wise, TaxVisitor is applied to object hierarchy. The job of TaxVisitor is to calculate tax based on object type visited. The crucial observation here is an object e.g., Liquor accepts the visitor and uses the visitor to call back the operation hierarchy (visit.visit(*this)), using self as an argument.
Let’s explore the code:
Credit: Design Patterns: Elements of Reusable Object-Oriented Software (By GoF),