“建筑”一书说:
When using dynamically typed languages like Ruby and Python ... dependency inversion does not require either the declaration or the inheritance of interfaces.
但我不明白,这本书没有举任何例子。
我的理解是,如果A级取决于违反DIP的B级,我们就可以引入一个InterfaceC,那么我们就获得这样的东西。
ClassA ---> InterfaceC <--- ClassB
I ve also looked at some examples on the internet, like this one that attempts dependency injection between PurchaseHandler
and PayPal
, https://duncan-mcardle.medium.com/solid-principle-5-dependency-inversion-javascript-7b054685f7cb
class PurchaseHandler {
processPayment(paymentDetails, amount) {
const paymentSuccess = PaymentHandler.requestPayment(
paymentDetails,
amount
);
if (paymentSuccess) {
// Do something
return true;
}
// Do something
return false;
}
}
class PaymentHandler {
requestPayment(paymentDetails, amount) {
// Complicated, PayPal specific logic goes here
return PayPal.requestPayment(paymentDetails, amount);
}
}
然而,这似乎只是增加了一个层次,导致这种依赖性图表:
PurchaseHandler ---> PaymentHandler ---> PayPal
这里没有发生任何转变......