Association (การเชื่อมโยง)
ความสัมพันธ์ระหว่างออบเจ็กต์ทั่วไป สามารถเป็น One-to-One, One-to-Many, Many-to-Many
ตัวอย่าง: Employee ↔ Project (Employee หลายคนทำ Project หนึ่ง, Project หนึ่งมี Employee หลายคน)
Composition (การรวมส่วน - Strong Ownership)
- Parent "เป็นเจ้าของ" Child อย่างแท้จริง
- ถ้า Parent ถูกทำลาย Child ก็หายไปด้วย (Life cycle ผูกมัดกัน)
- เป็นกรณีพิเศษของ Aggregation
- ความสัมพันธ์ "Part-of" (ส่วนของ)
ตัวอย่าง: Car (Parent) มี Engine (Child) → รถเสียหาย Engine ก็เสียหายตาม
Aggregation (การรวมกลุ่ม - Weak Ownership)
- Parent "มี" Child แต่ Child มีชีวิตอยู่ได้เอง
- Child สามารถอยู่ได้โดยไม่ต้องมี Parent
- ความสัมพันธ์ "Has-a" (มี)
ตัวอย่าง: Department (Parent) มี Employee (Child) → Employee ย้าย Department ได้, Department ลบได้ Employee ยังอยู่
สรุปเปรียบเทียบ
| ลักษณะ | Association | Aggregation | Composition |
|---|---|---|---|
| ความสัมพันธ์ | ทั่วไป | Has-a (弱) | Part-of (強) |
| Life cycle | อิสระ | อิสระ | ผูกมัดกับ Parent |
| Multiplicity | ทุกแบบ | มัก 1-to-Many | มัก 1-to-1 หรือ 1-to-Many |
| UML | เส้นลูกศร | Diamond ว่าง | Diamond เต็ม |
โค้ดตัวอย่าง
// Composition
class Car {
Engine engine = new Engine(); // สร้างภายใน Constructor
~Car() { /* engine ถูก GC พร้อมกัน */ }
}
// Aggregation
class Department {
List employees = new List(); // รับจากนอก
public void AddEmployee(Employee e) => employees.Add(e);
}