Visitor Design Pattern
For this week’s blogpost I will be discussing another design pattern, this time I will talk about the Visitor Design Pattern discussed on Source Making’s website. Essentially the Visitor design pattern allows you to add methods to classes of different types without much altering to those classes. Allowing you to make completely different methods depending on the class used. Because of this you can also define external classes that can then extend other classes without majorly editing them. Its primary focus is to abstract functionality that can be applied to an aggregate hierarchy of element objects. This promotes designing lightweight element classes due to the processing functionality being removed from the list of their responsibilities. New functionality can be added later easily by creating a new Visitor subclass. The implementation of Visitor beings when you create a visitor class hierarchy that defines a pure virtual visit() method in the abstract base class for each of the concrete derived classes in the aggregated node hierarchy. Form here each visit() method accepts a single argument – a pointer or reference to an original Element derived class. In short, each operation to be supported is modelled with a concrete derived class of the visitor hierarchy. Adding a single pure virtual accept() method to the base class of the Element hierarchy allows accept() to be defined to receive a single argument. The accept method also causes flow of control to find the correct Element subclasses, once a visit method is involved the flow of control is vectored to the correct Visitor subclass. The website listed below goes into much more detail into what exactly happens but here I summed it up so that most should be able to follow. But essentially the visitor pattern makes adding new operations easy, simply add a new Visitor derived class but if subclasses are not stable keeping everything in sync can be a bit of a struggle.
Example of Visitor Design Pattern
The example they use in the article is that based around the operation of a taxi company. When somebody calls a taxi company (literally accepting a visitor), the company dispatches a cab to the customer. Upon entering the taxi, the customer, or Visitor, is no longer in control of his or own transportation but the taxi driver is.
All in all, I thought this website was really good at explaining what the Visitor Design Pattern is. I have used this website before for previous research into design patterns and more.
https://sourcemaking.com/design_patterns/visitor
From the blog CS@Worcester – Matt's Blog by mattyd99 and used with permission of the author. All other rights reserved by the author.