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;

Benefits

  • 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

Drawbacks

  • 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).

List of Employee and Clerk objects on which we need to perform two actions (and maybe others in future):

  • increase income: increase the income of the Employee/Clerk by 30% and 10% respectively
  • increase vacation days: increase the vacation by 3 days for the Employee and by 1 day for the Clerk

Leave a Reply

Your email address will not be published. Required fields are marked *