Skip to content
BBaskaran

Visitor

Add new operations to an object structure without changing its classes.

Use it when

You need many unrelated operations over a stable set of element types.

/**
 * Visitor: add new operations over cart items without changing the item classes.
 *
 * Real-world scenario: a shop's cart holds books, electronics and food. The item
 * types rarely change, but the business keeps asking for new things to compute
 * over them: tax, packing instructions, and later gift wrapping or reports.
 * Each operation is a visitor class with one method per item type; items just
 * "accept" a visitor. A new operation is a new visitor, and the items stay as
 * they are.
 */

// Visitor: one method per element type.
interface CartVisitor {
  visitBook(book: Book): string;
  visitElectronics(item: Electronics): string;
  visitFood(item: Food): string;
}

// Elements: stable item types. Each one sends the visitor to the right method.
class Book {
  readonly title: string;
  readonly price: number;

  constructor(title: string, price: number) {
    this.title = title;
    this.price = price;
  }

  accept(visitor: CartVisitor): string {
    return visitor.visitBook(this);
  }
}

class Electronics {
  readonly name: string;
  readonly price: number;

  constructor(name: string, price: number) {
    this.name = name;
    this.price = price;
  }

  accept(visitor: CartVisitor): string {
    return visitor.visitElectronics(this);
  }
}

class Food {
  readonly name: string;
  readonly price: number;

  constructor(name: string, price: number) {
    this.name = name;
    this.price = price;
  }

  accept(visitor: CartVisitor): string {
    return visitor.visitFood(this);
  }
}

// Concrete visitors: each is one whole operation, kept in one place.
class TaxVisitor implements CartVisitor {
  visitBook(book: Book): string {
    return `${book.title}: no tax on books`;
  }

  visitElectronics(item: Electronics): string {
    return `${item.name}: 20% tax = $${(item.price * 0.2).toFixed(2)}`;
  }

  visitFood(item: Food): string {
    return `${item.name}: 5% tax = $${(item.price * 0.05).toFixed(2)}`;
  }
}

class PackingVisitor implements CartVisitor {
  visitBook(book: Book): string {
    return `${book.title}: standard envelope`;
  }

  visitElectronics(item: Electronics): string {
    return `${item.name}: bubble wrap, FRAGILE label`;
  }

  visitFood(item: Food): string {
    return `${item.name}: chilled box`;
  }
}

function clientCode(): void {
  const cart = [
    new Book("Clean Code", 30),
    new Electronics("Headphones", 80),
    new Food("Cheese", 12),
  ];

  for (const visitor of [new TaxVisitor(), new PackingVisitor()]) {
    console.log(`${visitor.constructor.name}:`);
    for (const item of cart) {
      console.log(`  ${item.accept(visitor)}`);
    }
  }
}

clientCode();

// Output:
// TaxVisitor:
//   Clean Code: no tax on books
//   Headphones: 20% tax = $16.00
//   Cheese: 5% tax = $0.60
// PackingVisitor:
//   Clean Code: standard envelope
//   Headphones: bubble wrap, FRAGILE label
//   Cheese: chilled box

How it works

RoleClassesWhat it does
ElementsBook, Electronics, FoodStable item types; accept(visitor) calls the visitor method for their own type
VisitorCartVisitorInterface with one visit method per item type
Concrete visitorsTaxVisitor, PackingVisitorEach is one whole operation over all item types, kept in one class
ClientclientCode()Runs each visitor over the cart; new operations need no item changes