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

Composition vs Aggregation ใน C#: ความสัมพันธ์ระหว่างออบเจกต์

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

ตารางเปรียบเทียบ

คุณสมบัติCompositionAggregation
OwnershipParent เป็นเจ้าของParent ไม่ใช่เจ้าของ
LifecycleChild ตายพร้อม ParentChild มี Lifecycle แยก
CreationParent สร้าง ChildChild สร้างภายนอก ส่งมา
Sharingไม่ Share ได้Share ได้หลาย Parent
CouplingGreen (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 จริง