Visitor Pattern

Francesco Ciulla - Mar 16 '20 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .