Problem: there are hierarchies with arbitrary depth and width (e.g. folders and files)

Solution: the composite pattern lets a Client treat an individual class called Leaf and Compositions of Leaf classes uniformly

Composite - structural design pattern that lets you compose objects into tree structures and then work with these structures as if they were individual objects.

<aside>

Applicability

image.png

image.png

The greatest benefit of this approach is that you dont need to care about the concrete classes ob objects that compose the tree. We can treat them all the same via the common interface.

Structure

image.png

  1. describes operations that are common to both simple and complex elements of the tree
  2. basic element, doesnt have sub-elements
  3. Composite (aka Container), element that has sub-elements: leafs or other containers. Container doesnt know the concrete classes of its children. Works with sub-elements only via the component interface
  4. works with all elements through the component interface: can work that way with both simple or complex elements of the tree.

image.png

<aside>

How to implement:

  1. Make sure that the core model of your app can be rep­re­sent­ed as a tree struc­ture. Try to break it down into sim­ple ele­ments and con­tain­ers. Remem­ber that con­tain­ers must be able to con­tain both sim­ple ele­ments and other containers.
  2. Declare the com­po­nent inter­face with a list of meth­ods that make sense for both sim­ple and com­plex components.
  3. Cre­ate a leaf class to rep­re­sent sim­ple ele­ments. A pro­gram may have mul­ti­ple dif­fer­ent leaf classes.
  4. Cre­ate a con­tain­er class to rep­re­sent com­plex ele­ments. In this class, pro­vide an array field for stor­ing ref­er­ences to sub-ele­ments. The array must be able to store both leaves and con­tain­ers, so make sure it’s declared with the com­po­nent inter­face type. While imple­ment­ing the meth­ods of the com­po­nent inter­face, remem­ber that a con­tain­er is sup­posed to be del­e­gat­ing most of the work to sub-ele­ments.
  5. Final­ly, define the meth­ods for adding and removal of child ele­ments in the container. Keep in mind that these oper­a­tions can be declared in the com­po­nent inter­face. This would vio­late the Inter­face Seg­re­ga­tion Prin­ci­ple because the meth­ods will be empty in the leaf class. How­ev­er, the client will be able to treat all the ele­ments equal­ly, even when com­pos­ing the tree. </aside>