Executing code based on the object type using the visitor pattern
The visitor pattern introduces the separation of algorithm execution from the object instance in question. This pattern is mentioned in the GoF’s book.
Motivation
The visitor pattern allows a client to define a new operation without changing the instance of the class it is working on. This pattern provides a way to separate the underlying code from the object structure. The separation practically results in providing the ability to add new operations to an existing object without any modifications to its structure.
Finding it in the JDK
Usage of the visitor pattern can be found in the java.base
module and the java.nio.file
package. The FileVisitor
interface used by the Files
utility class and its walkFileTree
method uses a pattern to traverse the directory structure and associated files.
Sample code
A vehicle’s security normally relies on the robustness of its sensors. The example shows...