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

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

Composition (การประกอบ) ใน C#

Composition เป็นรูปแบบความสัมพันธ์ "Has-A" แบบ Strong Ownership: Parent ควบคุม Lifetime ของ Child หาก Parent ถูกทำลาย Child ก็จะถูกทำลายไปด้วย

ตัวอย่าง: รถยนต์และเครื่องยนต์


public class Engine
{
    public void Start() => Console.WriteLine("Engine started");
    public void Stop() => Console.WriteLine("Engine stopped");
}

public class Car
{
    // Composition: Car เป็นเจ้าของ Engine (สร้างใน Constructor)
    private readonly Engine _engine = new Engine();
    
    public void StartCar()
    {
        Console.WriteLine("Car starting...");
        _engine.Start();
    }
    
    public void StopCar()
    {
        _engine.Stop();
        Console.WriteLine("Car stopped");
    }
    
    // เมื่อ Car ถูก GC, _engine ก็จะถูก GC ตามไปด้วย
}

// ใช้งาน
var car = new Car();
car.StartCar();
// Output:
// Car starting...
// Engine started

Composition vs Aggregation vs Association

ความสัมพันธ์ความหมายLifetimeตัวอย่าง
CompositionPart-of (Strong)Child ตายพร้อม ParentCar - Engine, House - Room
AggregationHas-A (Weak)Child มีชีวิตต่อได้Department - Employee
AssociationUse-AอิสระกันStudent - Course

ตัวอย่าง Aggregation (Weak)


// Aggregation: Department มี Employee แต่ Employee ไม่ตายพร้อม Department
public class Employee { public string Name; }

public class Department
{
    private List _employees = new List();
    
    public void AddEmployee(Employee emp) => _employees.Add(emp);
    // Employee ถูกสร้างนอก Department, สามารถย้ายไป Department อื่นได้
}

ข้อดีของ Composition

  • Encapsulation: ซ่อน Implementation Detail ของ Child
  • Single Responsibility: แยกหน้าที่ชัดเจน
  • Flexibility: เปลี่ยน Child Implementation ได้ง่าย (Strategy Pattern)
  • Testability: Mock Child ได้ง่าย (ถ้าใช้ Interface)

Design Principle: "Favor Composition over Inheritance"

GoF Design Patterns แนะนำให้ใช้ Composition มากกว่า Inheritance เพราะ Loose Coupling และ Flexibility สูงกว่า