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.
- Is this right? Can someone explain this to me a little better?
- When would I prefer one over the other?
Composition
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:
So as you can see you should choose between composition or aggregation depending on the type of ownership relationship.
Composite pattern
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
JPanelcan hold various controls like text fields, labels, lists, etc. but it can also hold otherJPanels 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).