Both are one way of extending a class.
In a composition relationship, the whole has sole responsibility for the disposition of its parts, or as you put it above, the whole "controls the lifetime of" the part. In order for the whole
to have "sole disposition" or "control the lifetime" of its parts, the whole must be the only object that knows of the parts existence.
C++ Code Example:
class Whole {
Part* part;
public:
Whole(): part( 0 ) { }
~Whole() { delete part; }
};
Part is created inside Whole class constructor and it is destroyed when whole is destroyed.
Real Life Example:
University and Departments have a composition relationship. When University is created all the departments are created with it. When University is removed departments will not have the existance of their own.
In aggregation relationship, the part object reference can be re-used. Usually creation of part object is not the responsibility of the ‘whole ‘ object. It would have been created somewhere else, and passed to the ‘whole’ object as a method argument. Whole object will not have control on the lifetime of the part object.
class Whole {
Part* part;
public:
Whole() { }
~Whole() { }
};
Real Life Example:
University and Professors are in aggregation relationship. When University is formed professors will come and join the University. But, when University is removed Professors will still exists and they can work in other Universities.
Categories
FollowersBlog Archive
Jobs
Find more freelance jobs
|
Wednesday, February 13, 2008
Subscribe to:
Post Comments (Atom)
|
Popular Posts
|
No comments:
Post a Comment