Contact Me

Visitor

 This pattern allows you to separate an operation from an object structure on which it operates. This can be useful when you want to perform operations on elements of an object structure without changing the structure itself, and when you want to add new operations to the object structure without modifying the structure itself.


Here is an example of the visitor pattern in JavaScript:


class Element {

accept(visitor) {

  visitor.visit(this);

}

}

class ConcreteElementA extends Element {

operationA() {

  console.log('Executing operation A...');

}

}

class ConcreteElementB extends Element {

operationB() {

  console.log('Executing operation B...');

}

}

class Visitor {

visit(element) {

  element.operationA();

}

}

class ConcreteVisitor extends Visitor {

visit(element) {

  element.operationB();

}

}

const element = new ConcreteElementA();

const visitor = new ConcreteVisitor();

element.accept(visitor);

// Output: 'Executing operation B...'


In this example, the Element class is a base class for elements of an object structure, and the ConcreteElementA and ConcreteElementB classes are concrete subclasses of the Element class. The Element class has an accept() method that accepts a visitor object and calls the visitor's visit() method with the element as an argument.

The Visitor class is a base class for visitors of the object structure, and the ConcreteVisitor class is a concrete subclass of the Visitor class. The ConcreteVisitor class overrides the visit() method to provide a custom implementation of the operation to be performed on the element.

To use the visitor pattern, we create instances of the Element and Visitor classes, and then call the accept() method of the element with the visitor as an argument. This causes the visitor's visit() method to be called with the element as an argument, allowing the visitor to perform the operation on the element.