Agile Software Development-principles, models and practices
The dependency inversion principle (DIP) describes that all classes should depend on abstract classes to avoid dependency on specific classes.
Circle c = new Circle (r );
Circle is a specific class, so the forces that create Circle violate DIP. Many specific classes are
It is very easy to change, depending on them, it will cause problems. This uses the Factory mode and the factory mode.
Instances of specific objects can be created only by relying on abstract interfaces.
The following is a specific example.
// Client. java
Package com. factory;
Import static org. junit. Assert .*;
Import org. junit. Test;
Public class Client {
@ Test
Public void testFactory (){
ShapeFactory sf = new ShapeFactoryImpl ();
Shape s = sf. make ("Circle ");
AssertTrue (s instanceof Circle );
}
}
// ShapeFactory. java
Package com. factory;
Public interface ShapeFactory {
Shape make (String shapeName );
}
// Shape. java
Package com. factory;
Public abstract class Shape {
}
// Circle. java
Package com. factory;
Public class Circle extends Shape {
}
// ShapeFactoryImpl. java
Package com. factory;
Public class ShapeFactoryImpl implements ShapeFactory {
@ Override
Public Shape make (String shapeName ){
If (shapeName. equals ("Circle ")){
Return new Circle ();
} Else {
Return null;
}
}
}