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

Delegation vs Inheritance ใน C#: เลือกใช้แบบไหนดี?

ทั้ง Delegation (การมอบหมาย) และ Inheritance (การสืบทอด) เป็นเทคนิคสำหรับการนำโค้ดกลับมาใช้ใหม่ (Code Reuse) แต่มีแนวคิดและการใช้งานที่ต่างกัน

Inheritance (การสืบทอด) - "Is-A" Relationship

คลาสลูก "เป็นประเภทหนึ่งของ" คลาสแม่

// Base Class
public class Animal { public void Eat() { ... } }

// Derived Class
public class Dog : Animal { public void Bark() { ... } }

// ใช้งาน
Dog d = new Dog();
d.Eat();  // สืบทอดมา
d.Bark(); // ของตัวเอง

ข้อดี

  • นำโค้ดกลับมาใช้ใหม่ได้โดยอัตโนมัติ
  • Polymorphism - ใช้ Derived Class แทน Base Class ได้
  • โครงสร้างชัดเจน สร้างลำดับชั้นได้

ข้อเสีย

  • Couting สูง - คลาสลูกพึ่งพา Implementation ของคลาสแม่
  • แข็งแกร่ง - ยากต่อการเปลี่ยนแปลงรันไทม์
  • Single Inheritance - C# สืบทอดคลาสได้เพียงตัวเดียว

Delegation (การมอบหมาย) - "Has-A" Relationship

คลาสหนึ่ง "มี" อีกคลาสหนึ่ง และมอบหมายงานให้คลาสนั้นทำ

// Interface สำหรับการมอบหมาย
public interface ILogger { void Log(string msg); }

// Implementation
public class FileLogger : ILogger { public void Log(string msg) { ... } }
public class ConsoleLogger : ILogger { public void Log(string msg) { ... } }

// ใช้ Delegation
public class Application
{
    private readonly ILogger _logger; // "มี" Logger
    
    public Application(ILogger logger) // Inject ผ่าน Constructor
    {
        _logger = logger;
    }
    
    public void Run()
    {
        _logger.Log("App started"); // มอบหมายงานให้ Logger
    }
}

ข้อดี

  • Loose Coupling - เปลี่ยน Implementation ได้ใน Runtime
  • ยืดหยุ่น - รวมพฤติกรรมหลายแบบได้ (Composition over Inheritance)
  • ทดสอบง่าย - Mock Interface ได้
  • หลีกเลี่ยงปัญหา Diamond Problem

เมื่อไหร่ควรใช้แบบไหน?

สถานการณ์แนะนำ
ความสัมพันธ์ "Is-A" ชัดเจน (Dog is Animal)Inheritance
ต้องการเปลี่ยนพฤติกรรม RuntimeDelegation
ต้องการรวมพฤติกรรมหลายอย่างDelegation (Composition)
Framework/Base Class LibraryInheritance (abstract base)
Business Logic / Application CodeDelegation (Dependency Injection)

หลักการ: "Favor Composition over Inheritance" - ให้ความสำคัญกับ Composition/Delegation มากกว่า Inheritance ในโค้ดประยุกต์