The Visitor design pattern is another behavioral pattern that simplifies access to an object’s data collections. Moreover, it is closely related to the Iterator design pattern. Unlike the Iterator pattern, the Visitor pattern makes client codes visit one data item at a time. In other words, it repeatedly calls some client codes for each of the data without exposing the client to the complexity of an object’s internal data.
An Object With Complex Collections of Data
We can use the example object with complex data collections from this Iterator Design Pattern post.
The Visitor Pattern Off The Gang of Four
The Gang of Four book states the Visitor design pattern’s intent succinctly.
Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.
Therefore, we create another object (A) representing an operation (method) that accepts an item of data of a specific type. Moreover, the object (B) that has the complex data calls the operation repeatedly for each data item. Hence, the operation simulates the act of visiting each data item. The other object (A) could then derive helpful information from each data item when the operation happens. For example, the total count of data items.
Since the Visitor design pattern requires object B to have a reference to object A, it is essential to use abstraction to decouple them. For example, we have a common interface that both use. As a result, we could create various kinds of object A to process the data item one at a time and derive other information.
Other Design Patterns
The Visitor design pattern is only one of the behavioral design patterns we can use to create maintainable software applications. Check out the other design patterns on Design Patterns Are The Ultimate Toolkit For Programmers.