Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Association, Composition และ Aggregation ใน C#

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 ยังอยู่

สรุปเปรียบเทียบ

ลักษณะAssociationAggregationComposition
ความสัมพันธ์ทั่วไป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);
}