Visitor cho phép thêm operation mới vào object structure mà không cần sửa class của các objects đó — tách algorithm khỏi data structure nó operates on.
- Cấu trúc:
interface Visitor { visitCircle(c: Circle): void; visitRectangle(r: Rectangle): void }— mỗi shape cóaccept(visitor: Visitor)gọi đúng visit method. - Vấn đề Visitor giải quyết: khi có stable object hierarchy (ít thêm class mới) nhưng cần thêm nhiều operations mới — với Visitor, thêm operation = thêm Visitor class mới mà không sửa Shape classes.
- Trade-off vs SOLID: Visitor tuân thủ OCP cho operations nhưng vi phạm OCP cho elements — khi thêm
Triangle, phải sửa tất cả Visitor. - Dùng khi: AST (Abstract Syntax Tree) processing — compiler, code analyzer, transformer; document model với nhiều export format.
- TypeScript compiler dùng Visitor cho AST traversal.
- Không dùng khi: object hierarchy thay đổi thường xuyên; khi chỉ cần 1-2 operations — polymorphism đơn giản hơn.
Visitor allows you to add new operations to an object structure without modifying the classes of the objects — it separates the algorithm from the data structure it operates on.
- Structure:
interface Visitor { visitCircle(c: Circle): void; visitRectangle(r: Rectangle): void }— each shape has anaccept(visitor: Visitor)method that calls the correct visit method. - The problem Visitor solves: when you have a stable object hierarchy (few new classes added) but need to add many new operations — with Visitor, adding an operation means adding a new Visitor class without touching the Shape classes.
- SOLID trade-off: Visitor follows OCP for operations but violates OCP for elements — adding a
Trianglerequires modifying every Visitor. - Use it for AST (Abstract Syntax Tree) processing — compilers, code analyzers, transformers — or for document models with many export formats.
- The TypeScript compiler uses Visitor for AST traversal.
- Avoid it when the object hierarchy changes frequently, or when only 1–2 operations are needed — simple polymorphism is cleaner.