i searched a lot about this but i couldn't find any answer that make me see the difference and the benefits of using dependency injection (not just Spring).
So, for example, if i've got this class:
public class Person {
private ISpeaker speaker = null;
public Person(ISpeaker speaker) {
this.speaker = speaker
}
public void doWelcome(){
this.speaker.sayHello();
}
}
public class Josh implements ISpeaker {
@Override
public void sayHello(){
System.out.println("Josh: Hello my friend!");
}
}
So, by my understanding, using injection i would have to inject to the Person class my implementation of ISpeaker, that would be Josh in this case. What i don't understand is why not just do this:
public void myGreetingApp() {
ISpeaker speaker = new Josh();
Person person = new Person(speaker);
person.doWelcome();
}
Can anybody tell me the difference of doing this and use dependency injection? and what benefits would it bring me? Thanks !
Aucun commentaire:
Enregistrer un commentaire