Skip to content

Latest commit

 

History

History

composite

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

Intend

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.

How it's done

UML

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

  1. Make sure the model of your app can be represented as a Tree.
  2. Declare the Component interface with the methods that make sense for both Leafs and Composites.
  3. Create Leaf classes to represent simple elements that do not have children.
  4. Create Composite classes with an underlying container for children, methods to add/remove children.
  5. Implement the Component methods in the Composite delegating the hard work to children.

Note : UML class diagram taken from here

Pros & cons

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.

Notes

Here are some usefull ressources :