web analytics

Association, Aggregation and Composition in OOAD

Options
@2017-04-10 11:28:28

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. The composition relationship is shown on a UML diagram as a filled diamond.

composition.png

Within the 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 the Engine.

 

@2019-04-24 09:12:05

Express aggregation in C#

To model the relationship between customers and addresses, it would make sense to 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 from the composition. Consider the following code:

public class Address
{
 . . .
}

public class Person

{

     private Address address;

     public Person(Address address)

     {

         this.address = address;

     }

     . . .

}

A 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, a Person does not manage the lifetime of an Address. If the Person is destroyed, the Address still exists. This scenario does map quite nicely to the real world.

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com