Corner of the Hyperspace
  • Home
  • Archive
  • Tags
  • About
  • robert-fekete
  • robert-fekete
  • rofekete
  • Visitor pattern
    Posted on April 8, 2019

    There is a lot of resources on the internet about design patterns and Visitor in particular. So, why am I writing a post about it?

    xkcd Standards

    My main pet peeve about the ones floating on the internet is that they are missing the main point, which is describing when to use them. The existing posts describe what the pattern is, they throw in a confusing UML diagram and then provide some code examples. Some code examples are on the right track, but they usually just blurb some lines out without real behavior. Other examples are just completely unfit to demonstrate the pattern. They even miss some components from the aforementioned UML diagram.

    Printing out some output is enough to show in which order different methods are called, but it ignores the key part. The behavior. The main reason to use a pattern is how your classes behave or how you want them to behave. One of the main design patterns categories is actually called “Behavioral patterns” for this very reason. Even though you have classes called ShoppingCart, Item, Book and Fruit, like in an example, they could represent completely different things in your business domain. You don’t use Visitor, because you have classes with names similar to the example. You use Visitor, because how these classes interact with each other.

    I’ll describe the Visitor pattern in this post and show a few realistic examples with actual behavior. Hopefully these examples will give you enough analogy, so you can recognize similar problems in the future and you will be able to successfully apply the Visitor pattern. I’ll also point out some of the properties of the pattern that can help you decide when to use or not to use the Visitor.

    Let’s get started.

    More...
© Robert Fekete 2019. All rights reserved.