Dependency Inversion Principle
About 251 wordsLess than 1 minute
2025-03-27
Definition
- High-level modules should not depend on low-level modules, both should depend on their abstractions.
- Abstractions should not depend on details, details should depend on abstractions.
Implementation Method
Introduce an abstract interface layer between high-level modules and low-level modules. The abstract interface is an abstraction of low-level modules, and low-level modules inherit or implement the abstract interface. In this way, high-level modules do not directly depend on low-level modules but on the interface layer.
- Depend on abstraction.
- Design interfaces rather than implementations. Use inheritance to avoid direct binding to classes.
- Avoid transitive dependencies. Use inheritance and abstract classes to eliminate dependencies.
Example
Counter Example
Consider a furnace regulator that reads the current temperature from one I/O channel and controls the furnace to continue heating or stop by sending instructions to another I/O channel.
const byte THERMONETER=0x86;
const byte FURNACE=0x87;
const byte ENGAGE=1;
const byte DISENGAGE=0;
void Regulate ( double minTemp,double maxTemp )
{
for ( ;; )
{
while ( in ( THERMONETER )> minTemp )
wait ( 1 ) ;
out ( FURNACE,ENGAGE ) ;
while ( in ( THERMONETER ) < maxTemp )
wait ( 1 ) ;
out ( FURNACE,DISENGAGE ) ;
}
}
Obviously, this code contains a lot of low-level implementation details, and this code is not very reusable.
Positive Example
void Regulate ( Thermometer t, Heater h, double minTemp,
double maxTemp )
{
for ( ;; )
{
while ( t.Read ( )> minTemp )
wait ( 1 ) ;
h.Engate ( ) ;
while ( t.Read ( ) < maxTemp )
wait ( 1 ) ;
h.Disengage ( ) ;
}
}
Contributors
Changelog
Copyright
Copyright Ownership:dingyuqi
License under:Attribution-NonCommercial-NoDerivatives 4.0 International (CC-BY-NC-ND-4.0)