O'Reilly logo

Mastering JavaScript Design Patterns by Simon Timms

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Visitor

The final pattern in this section is the visitor pattern. Visitor provides for a method of decoupling an algorithm from the object structure on which it operates. If we wanted to perform some action over a collection of objects that differ in type and we want to perform a different action depending on the object type, we would typically need to make use of a large if statement.

Let's get right into an example of this in Westeros. An army is made up of a few different classes of fighting persons (it is important that we be politically correct as there are many notable female fighters in Westeros). However, each member of the army implements a hypothetical interface called IMemberOfArmy:

interface IMemberOfArmy{
  printName();
}

A simple implementation ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required