ทั้ง Composition และ Aggregation เป็นรูปแบบของ Association (ความสัมพันธ์ "Has-A") แตกต่างกันที่ "วัฏจักรชีวิต" (Lifecycle) และ "ความเป็นเจ้าของ" (Ownership)
Composition (การประกอบ) - Strong "Has-A"
- Parent เป็นเจ้าของ Child - Child ไม่มีชีวิตแยกจาก Parent
- ถ้า Parent ถูก Destroy → Child ถูก Destroy ด้วย
- Child สร้างและจัดการโดย Parent ภายใน
- UML: Solid Diamond (◆──)
ตัวอย่าง: Car และ Engine
public class Engine
{
public void Start() => Console.WriteLine("Engine started");
}
public class Car
{
// Composition: Engine สร้างภายใน Car
private readonly Engine engine = new Engine();
public void StartCar()
{
engine.Start();
Console.WriteLine("Car started");
}
}
// ใช้งาน
Car car = new Car();
car.StartCar();
// เมื่อ car ถูก GC → engine ก็หายไปด้วย
Aggregation (การรวม) - Weak "Has-A"
- Parent ไม่ใช่เจ้าของ Child - Child มีชีวิตแยกต่างหาก
- Child สามารถมีอยู่ก่อน/หลัง Parent, และถูก Share ระหว่าง Parents ได้
- Parent รับ Reference ของ Child มา (ผ่าน Constructor/Property)
- UML: Hollow Diamond (◇──)
ตัวอย่าง: Employee และ Address
public class Address
{
public string Street { get; set; }
public string City { get; set; }
}
public class Employee
{
// Aggregation: รับ Address จากภายนอก
public Address Address { get; set; }
public Employee(Address address)
{
Address = address;
}
}
// ใช้งาน
Address addr = new Address { Street = "123 Main St", City = "Bangkok" };
Employee emp1 = new Employee(addr);
Employee emp2 = new Employee(addr); // Share Address เดียวกัน!
// ถ้า emp1 ถูก Destroy → addr ยังอยู่ (ถ้ามี emp2 Reference อยู่)
ตารางเปรียบเทียบ
| คุณสมบัติ | Composition | Aggregation |
|---|---|---|
| Ownership | Parent เป็นเจ้าของ | Parent ไม่ใช่เจ้าของ |
| Lifecycle | Child ตายพร้อม Parent | Child มี Lifecycle แยก |
| Creation | Parent สร้าง Child | Child สร้างภายนอก ส่งมา |
| Sharing | ไม่ Share ได้ | Share ได้หลาย Parent |
| Coupling | Green (Tight) | 鬆 (Loose) |
เมื่อไหร่ใช้แบบไหน?
- Composition: Part-Of Relationship (Engine เป็นส่วนของ Car, Room เป็นส่วนของ House)
- Aggregation: Has-A Relationship แต่อิสระ (Employee มี Address, Student มี Course, Library มี Book)
หลักการ: "Favor Composition over Inheritance" - แต่ระหว่าง Composition vs Aggregation ให้เลือกตาม Domain Logic จริง