codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🎭

Design Patterns

30 / 100 topics
19Introduction to Behavioral Patterns20Chain of Responsibility Pattern21Command Pattern22Interpreter Pattern23Iterator Pattern24Mediator Pattern25Memento Pattern26Observer Pattern27State Pattern28Strategy Pattern29Template Method Pattern30Visitor Pattern33Practical Exercises for Behavioral Patterns
Tutorials/Design Patterns/Visitor Pattern
🎭Design Patterns

Visitor Pattern

Updated 2026-05-15
10 min read

Visitor Pattern

Introduction

The Visitor pattern is a behavioral design pattern that allows you to add new operations to an existing class hierarchy without altering those classes. This is particularly useful when you have a complex object structure and want to perform various operations on the objects without modifying their classes.

In essence, the Visitor pattern separates algorithms from the objects on which they operate. It defines a new operation as a new visitor class that can traverse the object structure and execute its operations. This approach adheres to the Open/Closed Principle, which states that software entities should be open for extension but closed for modification.

Concept

The core idea behind the Visitor pattern is to encapsulate algorithms that operate on elements of an object structure into separate classes. These visitor classes define a method for each type of element in the object structure. The objects in the structure then accept a visitor, which calls the appropriate method defined by the visitor.

Here's a breakdown of the key components involved:

  1. Visitor: Declares a visiting operation for each class of ConcreteElement in the object structure.
  2. ConcreteVisitor: Implements each operation declared by Visitor, and stores the result of operations.
  3. Element: Defines an accept method that takes a visitor as an argument.
  4. ConcreteElement: Implements the accept method to call back the appropriate visiting operation on itself.
  5. ObjectStructure: Holds elements and may provide means for iterating through its elements.

Examples

Let's illustrate the Visitor pattern with a practical example. Suppose we have a simple object structure representing different types of shapes (Circle, Square) and we want to add operations like calculating area and perimeter without modifying the shape classes themselves.

Step 1: Define the Element Classes

First, let's define our Element classes, which represent the shapes:

JavaScript
1class Circle {
2constructor(radius) {
3 this.radius = radius;
4}
5
6accept(visitor) {
7 visitor.visitCircle(this);
8}
9}
10
11class Square {
12constructor(side) {
13 this.side = side;
14}
15
16accept(visitor) {
17 visitor.visitSquare(this);
18}
19}

Step 2: Define the Visitor Interface

Next, we define a Visitor interface with methods for each type of element:

JavaScript
1class ShapeVisitor {
2visitCircle(circle) {}
3visitSquare(square) {}
4}

Step 3: Implement Concrete Visitors

Now, let's implement concrete visitors that perform specific operations on the shapes:

JavaScript
1class AreaCalculator extends ShapeVisitor {
2constructor() {
3 super();
4 this.totalArea = 0;
5}
6
7visitCircle(circle) {
8 this.totalArea += Math.PI * circle.radius ** 2;
9}
10
11visitSquare(square) {
12 this.totalArea += square.side ** 2;
13}
14}
15
16class PerimeterCalculator extends ShapeVisitor {
17constructor() {
18 super();
19 this.totalPerimeter = 0;
20}
21
22visitCircle(circle) {
23 this.totalPerimeter += 2 * Math.PI * circle.radius;
24}
25
26visitSquare(square) {
27 this.totalPerimeter += 4 * square.side;
28}
29}

Step 4: Use the Visitor Pattern

Finally, we can use these visitors to perform operations on our shape objects:

JavaScript
1const shapes = [new Circle(5), new Square(10)];
2
3const areaCalculator = new AreaCalculator();
4shapes.forEach(shape => shape.accept(areaCalculator));
5console.log('Total Area:', areaCalculator.totalArea);
6
7const perimeterCalculator = new PerimeterCalculator();
8shapes.forEach(shape => shape.accept(perimeterCalculator));
9console.log('Total Perimeter:', perimeterCalculator.totalPerimeter);

Output

Output
Total Area: 314.1592653589793
Total Perimeter: 62.83185307179586

What's Next?

In this tutorial, we explored the Visitor pattern and how it allows you to add new operations to a class hierarchy without modifying the classes themselves. This pattern is particularly useful in scenarios where you have a complex object structure and want to perform various operations on the objects.

To further deepen your understanding, consider working through practical exercises that involve implementing different types of visitors for more complex object structures. Additionally, exploring real-world applications of the Visitor pattern in existing projects can provide valuable insights into its benefits and limitations.

For more information, you can refer to design patterns books or online resources that offer detailed explanations and examples of the Visitor pattern and other behavioral patterns.


PreviousTemplate Method PatternNext Practical Exercises for Creational Patterns

Recommended Gear

Template Method PatternPractical Exercises for Creational Patterns