Compose objects into tree structures to represent part-whole hierarchies.
It lets clients treat individual objects and compositions uniformly.
You should use the Composite pattern in the following cases :
- The core model of your app can be represented as a tree.
- You want (or you want the Client) to perform operations on composite objects as if they were standard objects - that is interacting with them using a common interface.
Participants
- Component :
- Declares the interface for the objects in the composition.
- Implements the default behaviour for the common interface to all classes.
- Declares an interface for managing childs components.
- Leaf :
- An object of the composition that has no children.
- Defines the default behaviour of primitive objects.
- Composite :
- Defines behaviour for components having children.
- Stores the child components.
- Implements the child-related operations in the Component interface.
- Client : Manipulates the objects in the composition through the Component interface.
How to implement
- Make sure the model of your app can be represented as a Tree.
- Declare the Component interface with the methods that make sense for both Leafs and Composites.
- Create Leaf classes to represent simple elements that do not have children.
- Create Composite classes with an underlying container for children, methods to add/remove children.
- Implement the Component methods in the Composite delegating the hard work to children.
Note : UML class diagram taken from here
Pros
- You and your clients can work easily with complex structures.
- Open/Closed principle: It is easy to introduce new elements in the apps without breaking the existing code.
- Reduce code complexity by eliminating many loops over the homogeneous collection of objects.
Cons
- It might be difficult to provide a common interface for classes whose functionality differs too much. In certain scenarios, you’d need to overgeneralize the component interface, making it harder to comprehend.
Here are some usefull ressources :
- A great article on Source making
- A blog article showing an example using CRTP
- A Refactoring guru article.