Consider HogeInterface
and HogeLocal
that implements it.
Any method can be used.
In the case of Spring, you can easily switch by simply switching the profile to "local" or "production" by writing as follows.
//Interface part
public interface HogeInterface {
String hogePrint(); //Do not write the return value
}
@Component //If you add this annotation, it will be injected with DI as needed.
@Profile({"local"}) //For local
public class HogeLocal implements HogeInterface {
@Override
public String hogePrint() {
return "It's local";
}
}
@Component
@Profile({"production"}) //For production
public class HogeProduction implements HogeInterface {
@Override
public String hogePrint() {
return "It's production"; //Processing different from local
}
}
//Since it will be injected without permission, there is no need to rewrite here for both local and production.
@Autowired //If you add this annotation@Injects a suitable one from conmponent
public Fuga(final HogeInterface hoge) { //Only the interface is written here
system.out.println(hoge.hogePrint);
}
If you do not do DI as above, you have to write as follows.
public Fuga() {
HogeInterface hoge = new HogeLocal();
// HogeInterface hoge = new HogeProduction();
system.out.println(hoge.hogePrint);
}
It's troublesome because I have to comment out the implementation part that does new
as needed.
Also, it is not good because it depends on the implementation.
Think in the figure.
In a bad example, Fuga, which is upstream, depends on downstream.
If the specifications of the detailed parts of HogeLocal
and HogeProduction
are changed, the dependent Fuga will also have to be changed.
In the correct example, Fuga
depends only on HogeInterface
, so even if the specifications of HogeLocal and HogeProduction change, Fuga does not need to be modified as long as the HogeInterface format is maintained.
Notice that all the arrows point to the abstract Interface
.
If you use DI, you can make it ** loosely coupled ** because all classes depend on the abstraction Interface
.
Also, in the correct example, it can be seen that the arrow of dependence is directed to lower-> upper, not to upper-> lower dependence. This is called ** dependency reversal **.
Recommended Posts