UML class and object diagram In the above
UML class diagram, the Client class doesn't refer to the Leaf and Composite classes directly (separately). Instead, the Client refers to the common Component interface and can treat Leaf and Composite uniformly. The Leaf class has no children and implements the Component interface directly. The Composite class maintains a container of child Component objects (children) and forwards requests to these children (for each child in children: child.operation()). The object collaboration diagram shows the run-time interactions: In this example, the Client object sends a request to the top-level Composite object (of type Component) in the tree structure. The request is forwarded to (performed on) all child Component objects (Leaf and Composite objects) downwards the tree structure. ;Defining Child-Related Operations There are two design variants for defining and implementing child-related operations like adding/removing a child component to/from the container (add(child)/remove(child)) and accessing a child component (getChild()): •
Design for transparency: Child-related operations are defined in the Component interface. This enables clients to treat Leaf and Composite objects uniformly. But
type safety is lost because clients can perform child-related operations on Leaf objects. •
Design for type safety: Child-related operations are defined only in the Composite class. Clients must treat Leaf and Composite objects differently. But type safety is gained because clients
cannot perform child-related operations on Leaf objects. The GoF authors present a variant of the Composite design pattern that emphasizes
transparency over
type safety and discuss the tradeoffs of the two approaches. The type-safe approach is particularly palatable if the composite structure is fixed post construction: the construction code does not require transparency because it needs to know the types involved in order to construct the composite. If downstream, the code does not need to modify the structure, then the child manipulation operations do not need to be present on the Component interface.
UML class diagram . ;Component • is the abstraction for all components, including composite ones • declares the interface for objects in the composition • (optional) defines an interface for accessing a component's parent in the recursive structure, and implements it if that's appropriate ;Leaf • represents leaf objects in the composition • implements all Component methods ;Composite • represents a composite Component (component having children) • implements methods to manipulate children • implements all Component methods, generally by delegating them to its children . == Variation ==