Bỏ qua để đến nội dung

Interface và Abstract Class

Interface mô tả khả năng/hợp đồng. Abstract class là class nền có thể chứa code dùng chung. Một class có thể implement nhiều interface nhưng chỉ kế thừa một class.

interface ILogger
{
void Log(string message);
}
abstract class Animal
{
public abstract void Speak();
public void Sleep()
{
Console.WriteLine("Sleeping");
}
}
class ConsoleLogger : ILogger
{
public void Log(string message)
{
Console.WriteLine(message);
}
}
class Cat : Animal
{
public override void Speak()
{
Console.WriteLine("Meow");
}
}
Tiêu chíInterfaceAbstract Class
Mục đíchHợp đồng hành viClass nền dùng chung
Kế thừaImplement nhiều interfaceChỉ kế thừa một class
State/fieldHạn chếCó field/property
ConstructorKhông dùng như class thườngCó constructor
Khi dùngNhiều class khác nhau cùng khả năngCác class cùng họ, cần code chung
  • Dùng interface cho ILogger, IRepository, IPaymentProvider.
  • Dùng abstract class cho Animal, BaseEntity, ControllerBase.

Tách interface theo khả năng giúp class chỉ implement phần cần thiết.

interface IReadRepository<T>
{
Task<T?> FindAsync(int id);
}
interface IWriteRepository<T>
{
Task AddAsync(T entity);
}

C# hỗ trợ implementation mặc định trong interface, nhưng nên dùng tiết chế.

interface IClock
{
DateTime Now() => DateTime.Now;
}
abstract class ReportExporter
{
public void Export()
{
LoadData();
WriteFile();
}
protected abstract void LoadData();
protected abstract void WriteFile();
}
Câu hỏiChọn
Các class không cùng họ nhưng cùng khả năng?Interface
Cần nhiều implementation thay thế để test/DI?Interface
Cần field, constructor, protected helper?Abstract class
Cần code chung cho một family rõ ràng?Abstract class
Muốn implement nhiều hợp đồng cùng lúc?Interface
  • Cho quá nhiều method vào một interface.
  • Dùng abstract class chỉ để ép method, trong khi interface gọn hơn.
  • Nhầm abstract với virtual: abstract bắt buộc override, virtual có implementation mặc định.
  • Đưa state phức tạp vào base class làm lớp con bị ràng buộc khó sửa.
  • Đặt tên interface quá chung như IManager, IHelper.

interface, giao diện, abstract class, lớp trừu tượng, default interface member, template method, implements, override, contract, base class, oop, dependency injection