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 O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.