web analytics
Association, Aggregation and Composition in OOAD Options
codeling
Posted: Monday, April 10, 2017 11:28:28 AM

Rank:Advanced Member
Groups: Member
Joined: 12/11/2015
Posts: 770
Points: 3234

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.

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. 

aggregation.png

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.

 

Sponsor
Posted: Monday, April 10, 2017 11:28:28 AM
Users browsing this topic
Guest

Forum Jump
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.


© 2017 Digcode.com. All rights reserved.