Luna Tech

Tutorials For Dummies.

Composite Pattern


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.

一个统一的和每个 node interact 的方式。

Composite Pattern Characteristics

  1. Component: a common interface
  2. Leaf: a component without children, inherited from Component
  3. Composite: a component with children, inherited from Component, child is also a Component
  4. Client: uses the component


1. Implementation of Composite Pattern

Example Code


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.

Example code

3. Consume existing composite

Example code


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.