Visitor classes are commonly used to perform operations on a set of objects without modifying the structure of their underlying classes.
Visitor Design Pattern allows you to add new operations(behaviours) via Visitor classes to existing classes without modifying their structure. Instead of adding the operation within the existing class, you create a visitor class named as operation you want to have in existing class, so that the operation is externalised from a set of objects without modifying the structure of their underlying classes.
Visitor Design Pattern is more about adding new operations to existing classes via Visitor classes without modifying their structure, rather than adding new fields or methods directly to the classes themselves.
Continue readingConsider a system where you have a hierarchy of classes representing different shapes, like
Circle
,Rectangle
, andTriangle
. Each of these shapes implementsVisitable
interface(or its equivalent) to allow visitor classes to operate on them.