War
with strong connections (hard dependencies) .War
has two strong connections: Boltons
and Starks
. public class War { private Starks starks; private Boltons boltons; public War(){ starks = new Starks(); boltons = new Boltons(); starks.prepareForWar(); starks.reportForWar(); boltons.prepareForWar(); boltons.reportForWar(); } }
Boltons
and Starks
dependencies outside, through the constructor of the War
class. public class War { private Starks starks; private Boltons boltons; // (DI) - public War(Starks starks, Boltons boltons){ this.starks = starks; this.boltons = boltons; } public void prepare(){ starks.prepareForWar(); boltons.prepareForWar(); } public void report(){ starks.reportForWar(); boltons.reportForWar(); } }
War
class needs to know not only how to accomplish a specific task, but also where to look for the classes it needs to perform its tasks. If we provide everything necessary for the work to our class outside, then we will get rid of the previously considered problems. The class can easily work with any instances of other classes that it needs to perform tasks, and will simply be tested in isolation from them. In an application that uses dependency injection, objects will never search for dependencies or create them within themselves. All dependencies are provided to it or embedded in it ready to use.main()
method, as shown below. In Android, this is usually done in the onCreate()
method inside the Activity . public class BattleOfBastards { public static void main(String[] args){ Starks starks = new Starks(); Boltons boltons = new Boltons(); War war = new War(starks,boltons); war.prepare(); war.report(); } }
BattleOfBastards
class BattleOfBastards
we create the Boltons
and Starks
dependencies and Boltons
through the constructor into the War
class. The dependent class War
depends on the Boltons
and Starks
dependencies.Source: https://habr.com/ru/post/343658/
All Articles