Association, Aggregation and Composition in OOAD
Suppose we are going to model a car, it would make sense to say that an engine is part-of a car. Composition is shown on a UML diagram as a filled diamond.
Within composition, the lifetime of the part (Engine) is managed by the whole (Car), in other words, when Car is destroyed, Engine is destroyed along with it. So how do we express this in C#?
public class Engine
. . .
public class Car
Engine e = new Engine();
As you can see in the example code above, Car manages the lifetime of Engine.
To model the relationship between customers and addresses, it would make sense say a Customer 'has-a' Address instead of saying an Address is 'part-of' the Customer. Aggregation is shown on a UML diagram as an unfilled diamond.
So how do we express the concept of aggregation in C#? Well, it's a little different to composition. Consider the following code:
public class Address
. . .
public class Person
private Address address;
public Person(Address address)
this.address = address;
. . .
Person would then be used as follows:
Address address = new Address();
Person person = new Person(address);
Person person = new Person( new Address() );
As you can see, Person does not manage the lifetime of Address. If Person is destroyed, the Address still exists. This scenario does map quite nicely to the real world.
© 2020 Digcode.com. All rights reserved.