I am finishing a course on design patterns, and while reviewing the notes came across something I missed during the semester: Composite vs. Composition. What I managed to understand is that composite is when an object actually encapsulates whole objects, while composition is when it only holds pointers to them.
This is a design concept (not really a pattern). This term is used when you want to describe one object containing another one. It occurs very often in Composition over inheritance discussion.
Moreover, composition implies strong ownership. One objects owns (i.e. manages the lifecycle) of another object. When parent is destroyed, all children are destroyed as well. If there is no such strong relationship (children can outlive parent) we are talking about aggregation.
Quoting great example in Wikipedia:
For example, a university owns various departments (e.g., chemistry), and each department has a number of professors. If the university closes, the departments will no longer exist, but the professors in those departments will continue to exist. Therefore, a University can be seen as a composition of departments, whereas departments have an aggregation of professors. In addition, a Professor could work in more than one department, but a department could not be part of more than one university.
So as you can see you should choose between composition or aggregation depending on the type of ownership relationship.
This is a GoF design pattern describing a parent-child strong relationship where the child can be a simple node or a container of other nodes (possibly containing other children).
It is very common in GUI and tree like structure. E.g. in Java Swing a JPanel
can hold various controls like text fields, labels, lists, etc. but it can also hold other JPanel
s which, in turn, can contain simple components and even more nested panels.
Typically Composite design pattern uses composition, however in some cases the parent does not have to own all children. To continue GUI example, you can take one panel and move it to another place (change the parent).