Composition (การประกอบ - Strong Ownership)
- ความสัมพันธ์ **"Part-Of"** (เป็นส่วนประกอบ)
- Parent เป็นเจ้าของ Child แบบสมบูรณ์
- Child ไม่มี Lifetime แยกจาก Parent
- ถ้า Parent ถูก Destroy → Child ถูก Destroy ด้วย
ตัวอย่าง: Car และ Engine
public class Engine
{
public void Start() => Console.WriteLine("Engine started");
}
public class Car
{
private Engine _engine = new Engine(); // สร้างภายใน (Owned)
public void Start()
{
_engine.Start();
Console.WriteLine("Car started");
}
}
// ใช้งาน
Car car = new Car();
car.Start();
// เมื่อ car ถูก GC, _engine ก็ถูก GC ด้วย
Aggregation (การรวม - Weak Ownership)
- ความสัมพันธ์ **"Has-A"** (มี)
- Parent มี Reference ไปยัง Child
- Child มี Lifetime แยกต่างหาก
- Child อาจถูก Share ให้ Parent หลายตัว
ตัวอย่าง: Employee และ Address
public class Address
{
public string Street { get; set; }
public string City { get; set; }
}
public class Employee
{
private Address _address;
// รับ Address จากภายนอก (Injected)
public Employee(Address address)
{
_address = address;
}
public Address Address => _address;
}
// ใช้งาน
var addr = new Address { Street = "123 Main St", City = "Bangkok" };
var emp1 = new Employee(addr);
var emp2 = new Employee(addr); // Share Address เดียวกัน
// addr ยังอยู่ได้แม้ emp1/emp2 หายไป
ตารางเปรียบเทียบสรุป
| ลักษณะ | Composition | Aggregation |
| UML Symbol | Filled Diamond ◆ | Empty Diamond ◇ |
| Ownership | Strong (Exclusive) | Weak (Shared) |
| Lifetime | Child ตายกับ Parent | Child มีชีวิตแยก |
| Creation | Parent สร้าง Child เอง | Child สร้างภายนอก Inject เข้า |
| ตัวอย่าง | House-Room, Car-Engine | Employee-Address, Student-Course |
Implementation ใน C#
// Composition - ใช้ Field 初始化ใน Constructor
class Parent { private Child _child = new Child(); }
// Aggregation - รับผ่าน Constructor/Property
class Parent { private Child _child; public Parent(Child c) => _child = c; }