Visitor Pattern

Visitor Pattern provides a uniformed interface for visiting different data or objects while allowing detailed operations in concrete visitors to vary. Visitor Pattern is usually used with composites, and it is widely used for walking through data structures like abstract syntax tree (AST). But to make it easier for those who are not familiar with compiler stuff, we will provide a simpler example.

Consider a DOM-like tree containing multiple elements to render:

[ 
  Text { 
    content: "Hello, " 
  }, 
  BoldText { 
    content: "TypeScript" 
  }, 
  Text { 
    content: "! Popular editors:\n" 
  }, 
  UnorderedList { 
    items: [ 
      ListItem { 
        content: "Visual Studio Code" 
      }, 
      ListItem { 
        content: "Visual Studio" 
      }, 
      ListItem { 
        content: "WebStorm" 
      } 
    ] 
  } 
] 

The rendering result ...

Get TypeScript Design Patterns now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.