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 (https://erichelin.wordpress.com/2017/02/20/javascript-command-design-pattern/).

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.

screen-shot-2017-02-28-at-10-10-43-pm

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

screen-shot-2017-02-28-at-10-09-12-pm

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

screen-shot-2017-02-28-at-9-57-30-pm

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

screen-shot-2017-02-28-at-10-12-18-pm

Stay tuned!

References

  1. https://dzone.com/articles/design-patterns-visitor
Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

w

Connecting to %s