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

Aggregation ใน C# คืออะไร

Aggregation (การรวม) คือความสัมพันธ์ "Has-A" แบบ Weak Ownership - Object หนึ่งมีอีก Object หนึ่ง แต่ทั้งสองมี Lifetime แยกกัน

ตัวอย่าง: Employee และ Address

public class Address
{
    public string Street { get; set; }
    public string City { get; set; }
    public string Country { get; set; }
}

public class Employee
{
    private Address _address;
    
    // รับ Address จากภายนอก (Dependency Injection)
    public Employee(Address address)
    {
        _address = address;
    }
    
    public Address Address => _address;
}

// ใช้งาน
var address = new Address { Street = "123 Main St", City = "Bangkok" };
var emp = new Employee(address);

// Address ยังใช้งานได้แม้ Employee ถูก Dispose
address.City = "Chiang Mai";

ลักษณะสำคัญ

  • Weak Ownership - Parent ไม่เป็นเจ้าของ Child แบบสมบูรณ์
  • Independent Lifetime - Child มีชีวิตอยู่ได้แยกจาก Parent
  • Shared Reference - Child อาจถูก Share ให้ Parent หลายตัว
  • Directional - Employee มี Address แต่ Address ไม่รู้ Employee

Aggregation vs Composition

ลักษณะAggregationComposition
ความสัมพันธ์Has-A (Weak)Part-Of (Strong)
LifetimeแยกกันChild ตายเมื่อ Parent ตาย
ตัวอย่างEmployee ↔ AddressCar → Engine
UMLEmpty Diamond ◇Filled Diamond ◆

Composition Example

public class Engine { }
public class Car
{
    private Engine _engine = new Engine(); // สร้างเอง ภายใน
    // Engine ตายพร้อม Car
}