Professional Documents
Culture Documents
Courscomposant2 Spring1
Courscomposant2 Spring1
Courscomposant2 Spring1
Dependency Injection
Sami Bhiri
Outline
• Decoupling interfaces from implementations
• Dependency resolution
• Dependency resolution : definition
• Dependency resolution : modes
April 20 2
Decoupling interfaces from
implementations
April 20 3
Open/Closed principle
April 20 4
Coupling to classes
April 20 5
Coupling to classes
April 20 6
Coupling to classes
April 20 7
Coupling to classes = Strong coupling
April 20 8
Coupling to interfaces
April 20 9
Coupling to interfaces
The attribute neg can be
assigned to any class of type INegotiator
April 20 10
Coupling to interfaces = towards loose
coupling
• Coupling to interfaces is a first step towards loosely coupling
• Open to extension, closed to modification
April 20 11
Dependency resolution
April 20 12
Dependency resolution : definition
• Dependency occurs between an object of class C1 and an object of
class C2 if :
• C1 has an attribute of type C2
• C1 extends C2
• C1 calls a method of C2
• Dependency is transitive
April 20 13
Dependency resolutions : example
Provided interface
April 20 14
Dependency resolution: modes
• Static instantiation
• Hard coded
• Dependency injection
• Constructor based
• Property setting based
• Dynamic instantiation
• Programmatically
• Framework based
April 20 15
Hard coded dependency resolution
package modulaire;
• The dependency is resolved
public class Broker implements IBroker { inside the component itself
private INegotiator neg;
• The component is strongly
public Broker(){ coupled to one class
neg = new Negotiator();
}
• Bad resolution to be avoided
public double getBrokerPrice(String productRef){
return 1.07*neg.getStorePrice(productRef);
}
}
April 20 16
Dependency injection : constructor based
public class Broker implements IBroker { public class Facade {
April 20 19
Dependency injection : property setting
based
public class Broker implements IBroker { public class Facade {
private static IBroker myBroker;
private INegotiator neg; public static void main(String[] args){
myBroker = new Broker();
public void setNeg(INegotiator neg) {
this.neg = neg; ((Broker) myBroker).setNeg(new
} NegotiatorCheaper());
April 20 21
Dynamic dependency injection :
framework based
April 20 22