Composite Pattern

Tak Yu Chan (Franky)
2 min readNov 1, 2021
Photo by veeterzy on Unsplash

Intent

Be able to treat objects with whole-part relationship uniformly.

We might face nested classes hierarchies that are hard for the clients to do some unify operation on them such as iterating them as the sub tress are not in the same pattern.

Composite Pattern comes to the rescue by allowing us to compose objects into tree structures that consist with composite objects and leaf objects, an interface will be placed on top of composite so that composite can be transparent and client can perform most of the methods to both of them uniformly.

Entities

We compose objects into tree structures which can have node and leaf.

Node (Composite): Object with children object

Leaf: Object without children object

Standardise

The goal is to understand in the nested object hierarchy, node and root are the only entities, standardising that allows client to perform unify action on them easily such as iteration.

Both node and leaf will implement the same interface (xxxComponent etc.), if the method from the parent interface doesn’t make sense to the node or leaf, then throwing exception is acceptable.

Trade off

+ Gained the benefit of uniform and make it easy for user to operate unify operations

- Reduce type safety as now client can be mistakenly add leaf into node.

- SRP, leaf and node get methods from the interface that they might not need

--

--