How can you use the Composite and Visitor patterns together?

Answer

The Composite + Visitor combination is one of the most powerful pattern pairings in software design. Composite creates a tree structure (AST, file system, UI widget tree, document model) where both leaves and composites share a common interface. The limitation of Composite alone is that adding a new operation (like "calculate size" or "render to HTML") requires modifying every node class. Visitor solves this: each node's accept(Visitor v) calls the appropriate v.visitLeaf() or v.visitComposite() method via double dispatch, and the Visitor class contains all the logic for one operation. Adding a new operation means adding a new Visitor class — no existing node classes are touched. Compilers use this combination extensively: an AST (Composite) is traversed by type-checking, optimization, and code-generation visitors, each a separate class with no changes to the AST node classes.