Dependency injection(簡稱DI)是一種軟體設計模式的一種,目前在Android Studio編寫的套件中有幾個就是DI,像是我後面會說到的Dagger2、Hilt,這兩個都是DI架構的工具套件。
依賴注入是讓物件之間的依賴關係降低耦合程度,高耦合的物件關係會在之後重建或修改程式碼時會有"牽一髮而動全身
"的效果,所以依賴注入可以提高程式碼的可重複利用性。
這邊先舉兩個類別 A 和 B ,當一個類別 B 要使用到另一個類別 A 的方法時,在沒有建立任何架構的情況下會使用直接呼叫並且使用new
的方式來取得。
組成Window的原料有玻璃材質和塑膠材質
public class Glass {
public Glass() {
}
public void glass() {
Log.e("TAG", "glass OK");
}
}
public class plastic {
public plastic() {
}
public void plastic() {
Log.e("TAG", "plastic OK");
}
}
public class Window {
private Glass glass;
private plastic plastic;
public Window(Glass glass, plastic plastic) {
this.glass = glass;
this.plastic = plastic;
}
public void printWindow() {
Log.e("TAG", "printWindow: Window OK");
glass.glass();
plastic.plastic();
}
}
組成Door的原料有木頭材質
public class wood {
public wood() {
}
public void wood() {
Log.e("TAG", "wood OK");
}
}
public class Door {
private wood wood;
public Door(wood wood) {
this.wood = wood;
}
public void printDoor() {
Log.e("TAG", "printDoor: Door OK");
wood.wood();
}
}
最後注入Window和Door組成House
public class House {
private Window window;
private Door door;
public House(Window window, Door door) {
this.window = window;
this.door = door;
}
public void printHouse() {
Log.e("TAG", "House OK");
window.printWindow();
door.printDoor();
}
}
public class MainActivity extends AppCompatActivity {
private Glass glass = new Glass();
private plastic plastic = new plastic();
private wood wood = new wood();
private Door door = new Door(wood);
private Window window = new Window(glass, plastic);
private House house = new House(window, door);
@Override
protected void onCreate(Bundle savedInstanceState) {
// ...省略
house.printHouse();
}
}
以上是我今天的Dependency injection(DI)的文章,明天會開始進入Dagger2套件的說明,我大致會分成3個部分進行說明、各註解標的意思與作用、架構實作。