Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 31

Software Design & Analysis

Lecture 4

1
Object Associations
• An association relates, links or attaches
different objects
• Example
– Teacher and Computer
– Department and Employees
– Students and courses

2
Types of Associations
• Simple association

• Aggregation

• Composition

3
Simple Association
• A simple association simply relates two or
more objects

• This is the weakest kind of association

4
Example

owns
Teacher Computer
1 1

register
Student Course
n n

5
Aggregation
• This is a stronger kind of association

• There is a part-whole relationship between


the participating objects

• The aggregate object owns the parts

6
Examples

Vehicle Part
n

Country Region
n

7
Composition
• Composition is a stronger kind of aggregation
– Part-whole relation
– Lifetime binding
– Information hiding
– No sharing

8
Example
Building Room
n

Address
street
city
Emp
province
n country
phone
email

9
class Building {
private:
Room r[10];
...
};

10
Summary
Simple Aggregation Composition
Relationship Yes Yes Yes
Part-whole Yes Yes
Lifetime binding Yes
Information hiding Yes
No sharing Yes

11
Implementation of Association
class Teacher {
private:
Computer* c;
public:
void add(Computer* c) {
this->c = c;
}
...
};
12
Implementation of Association ...
class Computer {
private:
Teacher* t;
public:
void add(Teacher* t) {
this->t = t;
}
...
};
13
Implementation of Association ...
int main() {
Teacher t1(..), t2(..);
Computer c1(..), c2(..), c3(..);
t1.add(&c2);
c2.add(&t1);
t2.add(&c2);
return 0;
}

14
Implementation of Composition
• Two ways
– Using objects
– using pointers

15
Composition using pointers
• Make sure characteristics of “containment by
value”

16
Implementation of Composition

List Node
n

17
Incorrect Implementation of Composition

class List {
private:
Node *head, *tail;
...
public:
void add(Node* n) {
tail->next = n;
tail = tail->next;
}
18
Implementation of Composition ...
class List {
private:
Node *head, *tail;
...
public:
void add(int x) {
tail->next = new Node(x);
tail = tail->next;
}
19
Implementation of Composition ...
~List() {
Node* ptr = head;
while (ptr != tail) {
delete ptr;
ptr = ptr->next;
}
}

20
Implementation of Composition ...
int main() {
List ls, ls2;
ls.add(10);
ls.add(20);
...
ls2.add(..);
return 0;
}

21
Implementation of Aggregation
• Same as that of simple association

22
Question
• Why aggregation?

23
Answer
• Aggregation increases readability

24
Example

NewClass2 NewClass4

Vehicle

NewClass3
NewClass5

25
Example ...

NewClass2 Component

Vehicle

NewClass3
NewClass5

26
Answer ...
• Aggregation provides another form of
abstraction

27
Example

Source: OOSE by Lethbridge & Laganiere


28
Note
• Type of association might change depending
upon the context!

• In case of doubt, select a weaker relationship

29
Example

Patient Organ
n

Liver Heart Kidney Lungs

30
The End

31

You might also like