Interface và Abstract Class
Ghi nhớ nhanh
Phần tiêu đề “Ghi nhớ nhanh”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.
Cú pháp
Phần tiêu đề “Cú pháp”interface ILogger{ void Log(string message);}
abstract class Animal{ public abstract void Speak();
public void Sleep() { Console.WriteLine("Sleeping"); }}Ví dụ
Phần tiêu đề “Ví dụ”class ConsoleLogger : ILogger{ public void Log(string message) { Console.WriteLine(message); }}class Cat : Animal{ public override void Speak() { Console.WriteLine("Meow"); }}So sánh
Phần tiêu đề “So sánh”| Tiêu chí | Interface | Abstract Class |
|---|---|---|
| Mục đích | Hợp đồng hành vi | Class nền dùng chung |
| Kế thừa | Implement nhiều interface | Chỉ kế thừa một class |
| State/field | Hạn chế | Có field/property |
| Constructor | Không dùng như class thường | Có constructor |
| Khi dùng | Nhiều class khác nhau cùng khả năng | Các class cùng họ, cần code chung |
Khi nào dùng?
Phần tiêu đề “Khi nào dùng?”- Dùng interface cho
ILogger,IRepository,IPaymentProvider. - Dùng abstract class cho
Animal,BaseEntity,ControllerBase.
Interface nhiều hành vi nhỏ
Phần tiêu đề “Interface nhiều hành vi nhỏ”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);}Default interface member
Phần tiêu đề “Default interface member”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 có template method
Phần tiêu đề “Abstract class có template method”abstract class ReportExporter{ public void Export() { LoadData(); WriteFile(); }
protected abstract void LoadData(); protected abstract void WriteFile();}Quy tắc chọn nhanh
Phần tiêu đề “Quy tắc chọn nhanh”| Câu hỏi | Chọ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 |
Lỗi thường gặp
Phần tiêu đề “Lỗi thường gặp”- 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
abstractvớivirtual: 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.
Tham khảo chính thức
Phần tiêu đề “Tham khảo chính thức”Từ khóa tìm kiếm
Phần tiêu đề “Từ khóa tìm kiếm”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