---
name: visitor
description: This skill should be used when the user asks about "visitor pattern", "when to use visitor", "implement visitor", "double dispatch", "add operations", or mentions needing to add operations to object structures without modifying them.
version: 1.0.0
---

# Visitor Pattern

## What Is It
The Visitor pattern represents an operation to be performed on elements of an object structure. It lets you define new operations without changing the classes of the elements on which it operates, using double dispatch.

## When to Use
- **Compiler AST processing** - Type checking, code generation, optimization
- **Document processing** - Export to different formats (HTML, PDF, plain text)
- **Object structure traversal** - Reporting, validation, transformation
- **Shopping cart** - Different pricing/discount calculations
- **File system** - Search, size calculation, indexing
- **UI component trees** - Rendering, event handling, serialization

## When NOT to Use
- **Stable object structure** - Rarely add new element types
- **Simple operations** - Direct method calls are clearer
- **Frequent new element types** - Requires updating all visitors
- **Performance critical** - Double dispatch has overhead

## How to Implement

### Implementation Steps
1. Create a visitor interface with visit methods for each element type
2. Create element interface with accept method that takes a visitor
3. Concrete elements implement accept to call visitor's specific method
4. Concrete visitors implement operations for each element type

### TypeScript Implementation

```typescript
// Visitor interface
interface Visitor {
  visitText(element: TextElement): void;
  visitImage(element: ImageElement): void;
}

// Element interface
interface Element {
  accept(visitor: Visitor): void;
}

// Concrete element
class TextElement implements Element {
  constructor(public text: string) {}

  accept(visitor: Visitor): void {
    visitor.visitText(this);
  }
}

// Concrete visitor
class ExportVisitor implements Visitor {
  visitText(element: TextElement): void {
    console.log(`<p>${element.text}</p>`);
  }

  visitImage(element: ImageElement): void {
    console.log(`<img src="${element.src}" />`);
  }
}
```

## Code Examples
See `examples/` directory for runnable TypeScript implementations:
- `examples/visitor.ts` - Basic implementation with document elements
- `examples/visitor-advanced.ts` - Real-world example with AST processing

## Related Patterns
- **Composite** - Visitors often work with Composite structures
- **Interpreter** - May use Visitor for operations on AST
- **Command** - Visitor is like externalized operations
