# Visitor

> Add new operations to an existing class hierarchy without modifying those classes — the Visitor carries the new behavior and visits each element.

- **Category**: Software Design
- **Subcategory**: behavioral
- **Canonical URL**: https://designpattern.fyi/patterns/visitor/

---

## Description
**Intent**: Separate operations from the objects they operate on so you can add new operations without touching the class hierarchy.

**Context**: You have a document tree (paragraphs, images, tables, headings) and you keep needing to add new operations: XML export, HTML export, word count, accessibility audit. Adding a new method to every node class every time is a maintenance nightmare.

**Solution**: Each element class has an `accept(visitor)` method that just calls `visitor.visitElement(this)`. Visitors implement a `visit` method for each element type. To add a new operation, write a new Visitor class — zero changes to the element hierarchy.


## Use Cases
Use when you have a stable class hierarchy (AST nodes, document tree, shape hierarchy) but need to frequently add new operations across all elements.



## Implementation Example

```javascript
class Shape {
  accept(visitor) {}
}

class Dot extends Shape {
  accept(visitor) { visitor.visitDot(this); }
}

class XMLExportVisitor {
  visitDot(dot) { console.log("Exporting dot as XML"); }
}

```



## Trade-offs


### Advantages

- New operations are new Visitor classes — existing elements are untouched.

- Related behavior for multiple types is co-located in one Visitor class.




### Considerations & Drawbacks

- Adding or removing a class from the hierarchy requires updating every Visitor — the element hierarchy needs to be stable.







---
**Reference**: [Original Source](https://refactoring.guru/design-patterns/visitor)

