Problem without DI
class Restuarant{ Tea tea = new Tea(); tea.prepareHotDrink(); } class Tea{ public void prepareHotDrink(){ } }
Here we have tightly coupled object (Restaurant is dependent on Tea object)
Solution-
We can make an interface like
interface IHotDrink{ public void prepareHotDrink(); }
And then we can implement as follows:
class Restuarant{ IHotDrink hotdrink; Restuarant(IHotDrink hotdrink){ hotdrink = this.hotdrink; } tea.prepareHotDrink(); } class Tea implements IHotDrink{ public void prepareHotDrink(){ } }
We can solve this tightly coupled thing with two ways
1. Using the constructor way
2. Using the setter method way