Association, Aggregation and Composition in OOAD Options

codeling Posts: 1109 Points: 4668
Posted: Monday, April 10, 2017 11:28:28 AM

Express composition in C#

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.

composition.png

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.

 


codeling Posts: 1109 Points: 4668
Posted: Wednesday, April 24, 2019 9:12:05 AM

Express aggregation in C#

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);

or

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.

Users browsing this topic
Guest