Composite Pattern
2022-03-04
0. What is Composite Pattern?
Related to tree structures (or parent-child relationships), most common example is a file system.
Composite means we compose objects into tree structures.
The composite pattern enables clients to interact with individual objects or compositions of objects in a uniform fashion.
- individual object: leaf nodes without children
- compositions of objects: nodes with children, child can be leaf or composite
一个统一的和每个 node interact 的方式。
Composite Pattern Characteristics
- Component: a common interface
- Leaf: a component without children, inherited from Component
- Composite: a component with children, inherited from Component, child is also a Component
- Client: uses the component
Benefits
- Client can manipulate a single component at any level in the tree hierarchy, regardless of whether it’s a leaf or composite.
1. Implementation of Composite Pattern
Note
Pattern can have slightly different implementations but we should still be able to identify the pattern variations.
2. Building composite objects
Once the pattern is built, it’s easy to work with, but building the composite objects can be sometimes a bit confusing.
We can encapsulate the composite with a dedicated builder.
3. Consume existing composite
Summary
Composite is a useful pattern to work with tree structure in a uniform way, it can be used with other patterns like the builder pattern.