M4 · Trees and RecursionSession 8-9StructuralReshaped in KotlinOutline

Intent. Treat individual objects and compositions of objects uniformly.

In Kotlin. sealed interface with a child list; exhaustive when for the recursion.

Opens the tree module. Treat a leaf and a branch through the same interface and recursion becomes possible. Everything else in this module operates on the tree that Composite creates – Iterator walks it, Visitor adds operations to it, Interpreter is the special case where the tree is a grammar.

Structure

classDiagram
    class Component {
        <<interface>>
        +operation()
    }
    class Leaf {
        +operation()
    }
    class Composite {
        -children: List~Component~
        +operation()
        +add(c)
        +remove(c)
    }
    Component <|.. Leaf
    Component <|.. Composite
    Composite o--> Component : many children

Telling It Apart

Patterns whose structure looks the same but whose intent does not. See the Confusing Pairs reference.

  • Decorator — Keep the interface and add responsibilities, stackable at runtime.