Dependency Inversion Principle (DIP - Nguyên tắc Đảo ngược Phụ thuộc)
“Các lớp cấp cao không nên phụ thuộc vào các lớp cấp thấp. CẢ HAI nên phụ thuộc vào các trừu tượng. Các trừu tượng không nên phụ thuộc vào chi tiết. Chi tiết nên phụ thuộc vào các trừu tượng.”
Mục đích: giảm sự phụ thuộc giữa các phần của chương trình bằng trừu tượng (interface hoặc abstract class) để tách biệt module cấp cao và cấp thấp → các module thay đổi độc lập không ảnh hưởng nhau.
Trước khi áp dụng DIP
<?php
class EmailService {
public function sendEmail($message) { echo "Sending email: $message\n"; }
}
class Notification {
private $emailService;
public function __construct() {
// Phụ thuộc TRỰC TIẾP vào EmailService (và tự new bên trong!)
$this->emailService = new EmailService();
}
public function send($message) { $this->emailService->sendEmail($message); }
}
// Muốn gửi SMS thay vì email? Phải SỬA code lớp Notification → vi phạm DIPSau khi áp dụng DIP
<?php
interface MessageService {
public function sendMessage($message);
}
class EmailService implements MessageService {
public function sendMessage($message) { echo "Sending email: $message\n"; }
}
class SmsService implements MessageService {
public function sendMessage($message) { echo "Sending SMS: $message\n"; }
}
class Notification {
private $service;
// Phụ thuộc vào TRỪU TƯỢNG MessageService, inject từ ngoài vào
public function __construct(MessageService $service) {
$this->service = $service;
}
public function send($message) { $this->service->sendMessage($message); }
}
(new Notification(new EmailService()))->send("Hello via Email!");
(new Notification(new SmsService()))->send("Hello via SMS!");- Trừu tượng hóa: interface
MessageServicetrừu tượng hành vi gửi thông báo - Module cấp cao:
Notificationphụ thuộcMessageServicethay vìEmailService - Module cấp thấp:
EmailService,SmsServicetriển khaiMessageService
→ Dễ dàng thay thế/mở rộng cách gửi thông báo mà không thay đổi lớp Notification.
Liên quan
- SOLID - chữ D
- Inversion of Control - nguyên lý đi kèm không thể không nhắc
- Dependency Injection - kỹ thuật hiện thực
- Program to Interface - Tập trung vào trừu tượng - cùng tư tưởng