What is the Visitor Design Pattern?

Click for: original source

An article by Jakub Kapuscik about the visitor design pattern. The idea behind the visitor design pattern is to put parts of the code that have specific responsibilities outside of the class.

The most common use case for the pattern is reporting and exporting data to a given format. Those are very useful features that can easily get complex. They operate on data stored in an object but have very specific tasks to perform.

The single responsibility principle states that a class should have only one reason to change. If we want to add reporting or exporting on a structure of data, we will have at least two responsibilities.

Author work with example implementation in PHP. A visitor has the following elements:

  • Visitor (Visitor) – Defines the interface of visitors
  • Concrete Visitor (SickLeaveReport) – Concrete implementation of operations defined in the Visitor interface
  • Element (Visitable) – Defines the “accept” operation interface, taking Visitor as an argument
  • Concrete element (Student, University) – Concrete implementation of elements.

Source code is provided in GitHub repo. Good one!

[Read More]

Tags programming oop php web-development