About relationships between classes, what's the difference between Association, Aggregation and Composition?
About relationships between classes, what's the difference between Association, Aggregation and Composition?
The definitions are conceptual. In practice the important thing is that we have generic associations between objects and the term most often used is composition, even when in fact it is not one, formally speaking. Some small details will make one thing or another. The most important thing is to try to keep the coupling as low as possible. In this aspect the simple association is the most indicated ... when feasible.
Interestingly the terms are used to structure data but it is the algorithms that will define the real difference.
One example is the relationship between a teacher and a student. A student may have several teachers and one teacher may have several students. One does not depend on the other to exist. Teachers can exist without students and students can exist without teachers.
class Cliente {
var contatos = new List<Contato>();
AdicionarContato(Contato contato) {
contatos.Add(contato); //este contato independe deste cliente
}
}
One example is the relationship between teachers and departments. Departments can have several teachers. And the teacher can only be linked to a department. But they are independent. A teacher can exist without linking to a department and does not depend on teachers to exist.
class Cliente {
var notas = new List<NotaFiscal>();
EmitirNota(NotaFiscal nota) {
notas.Add(nota); //a nota existe sempre mesmo que o cliente não exista mais
}
}
An example is the relationship between a university and departments. Besides the university owning several departments, they can only exist if the university exists. There is a dependency.
class NotaFiscal {
var itens = new List<item>();
AdicionarItem(Produto produto, int quantidade) {
itens.Add(new Item(produto, quantidade); //este item só existe nesta nota
}
}
Thetermshavethisrelation:
Ilaterdiscoveredthatthereisalreadya
summarizing:
In association we have no owner. the objects have their own lifetimes. and child obJects are independent. or if there is any kind of hierarchical relationship and the objects can be called independently from each other
In aggregation we have only one owner. the objects have independent lifetimes. and child obJects belong to a single parent. or if there is a kind of unilateral hierarchical linkage. although the objects are still minimally independent
composition is identical to aggregation but lifetime is that of the owner. that is. if the owner is stopped. or others are also