JavaScript – Visitor Pattern

GitHub Code

Pattern two in this series will be the visitor pattern.  Why?  Well, I was asked about it a few months back and I couldn’t remember its finer points.  After this post, I will be much better able to answer the same question if it arises at my next pattern party 🙂

My understanding of the visitor pattern is it allows you to have something ‘visit’ a collection of un-related classes/objects and get actions performed on those unrelated classes/objects.  Remember, JavaScript out of the box is not very friendly towards interfaces, inheritance and other Object Oriented Programming (OOP) principles.  I am using the same method I did in the command pattern blog post to ‘simulate’ the use of an interface (

The main ‘components’ of this pattern are as follows:

  • An interface that allows each unrelated class to be ‘visited’. In my example, this is IAcceptVisitor.js.
    • Each unrelated class implements this interface so it can accept the accepting visitor.

NOTE: This is the ‘tie’ between the visitor and the unrelated class.  It is small, but it is still a dependency which I am not wild about.


  • An interface for the visitor.  In my example, this is Ivisit.js.  I have one visitor that ‘visits’ every class that will accept it.


NOTE: I amended this after the commit to take a system and not a group and name.

  • A concrete implementation for the visitor that goes to each unrelated class/object.  In my example, this is SystemVisitor.js


All of this is put together in visitor.js (a driver file of sorts).


Stay tuned!



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s