Visitor Design Pattern is one of the design pattern which is less used comparatively. “Behavioral pattern” that allows separating an algorithm from an object structure on which it operates. This means that we can add new operations to this object structure (even a list of heterogeneous classes) without modifying it.
The pattern aligns towards the Open/Closed Principle which states
software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. Object-Oriented Software Construction, Bertrand Meyer
based on wikipedia.. The visitor design pattern is a way of separating an operation from an object structure on which it operates. In essence, this pattern allows one to add new virtual functions to a family of classes without modifying the classes themselves;
- Follows the open/closed principle
- Allows a new operation to be defined without changing the implementation of the class
- A visitor object can have state
- If a new visitable object is added then all visitors need to be modified
Some real life examples
A ‘screen painter’ object (the visitor) that paints several widgets to the screen (the elements).
A HTML parser (visitor) that parses HTML nodes (the elements).
Clerk objects on which we need to perform two actions (and maybe others in future):
- increase income: increase the income of the
Employee/Clerkby 30% and 10% respectively
- increase vacation days: increase the vacation by 3 days for the
Employeeand by 1 day for the