Design Pattern Download: The Visitor Pattern

Matthew MacFarquhar
2 min readMay 23, 2022

--

The Visitor Pattern is a behavioral pattern used in software engineering when we want to gather some data from a class or set of classes, without writing specific methods based on the method of gathering this data.

Example

Imagine we have a system of classes for all the residences in NYC, the class contains some info like # baths, # beds etc… You decide that you want to be able to export this info into JSON and ask the class owner to write a method in these classes called exportToJSON. They push back on this request since they believe that it doesn’t make sense for that function to be in their classes and it also would open the door to more out of scope functions being added for exporting to say xml or csv. You decide instead to simply have them write a class called accept which will allow another class to poke around in the data. This poking around class will be our visitor and it will have methods for dealing with each type of domicile it is currently visiting.

When to use a Strategy?

  • When we want to interact with some class but don’t want to have visitor specific functions in the target classes.

What is the Strategy composed of?

  • The Visitor (json visitor)
  • The targets (house and apartment classes)

Implementation

The Targets

The Instances

Now you can crawl through all the overpriced apartments in Manhattan!

{"domiciles":[{"Beds":2,"Baths":1},{"Beds":5,"Baths":3},{"Floor":20,"Beds":2,"Baths":1},{"Floor":3,"Beds":1,"Baths":1},{"Beds":4,"Baths":2}]}}

--

--

Matthew MacFarquhar
Matthew MacFarquhar

Written by Matthew MacFarquhar

I am a software engineer working for Amazon living in SF/NYC.

No responses yet