DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Visitor Pattern
Francesco Ciulla
Francesco Ciulla

Posted on

Visitor Pattern

Visitor Pattern

Behavioral Design Pattern


Github: https://github.com/FrancescoXX/Design-Patterns-Visitor-Javascript

πŸ“ŒIntroduction

Visitor is a simple behavioral design pattern.

It gives a way to easily separate an algorithm from an object structure.

It is also useful to visit complex objects structures.


⚑️In short

Allows adding new functions, without modifying existing classes.

We create a visitor class/function, that implements the specializations of the virtual function.

The visitor takes the instance reference as input, and implements the goal through double dispatch.


πŸ’‘Intent

Separate algorithms from the objects on which they operate.


πŸ”§ Apply (when we want to)

  • Visit complex objects structure (inheritance)
  • Perform operations based upon concrete classes
  • Avoid pollution of concrete classes with many different operations
  • Have the ability to easily define new operations, without changing concrete classes

βœ…Pro

  • Open/Closed Principle (software entities should be open for extension, but closed for modification).
  • Separates operations that don't belong together.
  • Accumulate state: Visitors can mantain state across the hierarchy

⚠️Cons

  • Breaks encapsulation
  • Adding new concrete elements is hard
  • Requires a new method for all concrete visistors
  • Rely on the interface of the concrete element (might lack the access to the object's private fields)

πŸ† Great for

  • Visit complex object structure
  • Change existing object without breaking the current structure
  • Centralize logic

/** Visitor Pattern
 *
 */
class Sayan {
  constructor(name, power) {
    this.name = name
    this.power = power

    this.getPowerLevel = () => this.power;
    this.setPowerLevel = (power) => this.power = power;
    this.acceptVisitor = (functionVisitor) =>  functionVisitor(this);
  }
}

const goku = new Sayan("Goku", 100);
console.log(goku.getPowerLevel()); //100

//Define a Visitor Function
const Empower = (sayan) => sayan.setPowerLevel(sayan.getPowerLevel() * 100);

//Substitute the new function to the Mage object
goku.acceptVisitor(Empower);

//Now check the new power!
console.log(goku.getPowerLevel()); //10000 It's Over 9000!
Enter fullscreen mode Exit fullscreen mode

Github: https://github.com/FrancescoXX/Design-Patterns-Visitor-Javascript

Top comments (1)

Collapse
 
valvic66 profile image
Micu Valentin

It doesn't look safe that this.acceptVisitor method gives access to the this so being able to access and modify / alter any property. Is it a workaround?

We want your help! Become a Tag Moderator.
Check out this survey and help us moderate our community by becoming a tag moderator here at DEV.