android studio 30天学习笔记 -day 22-Dagger 前言

Dependency Injection

Dependency Injection中文翻译为依赖注入。主要解决两个类别耦合性过高的问题
(高耦合:当被依赖对象被修改时,依赖对象也会被修改)

依赖注入是指「被依赖物件透过外部注入至依赖物件的程序中使用」

举个例子:假设顾客今天来到ABC水果摊买水果,可以表示Customer的class用到ABCFruitStand的class abcfruitStand =new ABCFruitStand();,也等同於顾客依赖於ABC水果摊。
但当顾客觉得ABC水果摊的水果太贵了想换别家水果摊,这样ABCFruitStand的class会被更改,而Customer class里的方法也会跟着变动,假设其他的Customer也有用到ABCFruitStand的class,那麽要改的地方就会更多了。

//第一家水果摊
public class ABCFruitStand {

    private String fruit;
    public void sellFruit(String fruit){
        this.fruit=fruit;
        System.out.println(fruit+"一颗50块");
    }
}
// 第二家水果摊
public class GHEFruitStand {

    private String fruit;
    public void sellFruit(String fruit){
        this.fruit=fruit;
        System.out.println(fruit+"一颗50块");
    }
}

public class Customer {

    public void buy(){
        ABCFruitStand abcfruitStand =new ABCFruitStand();
        abcfruitStand.sellFruit("西瓜");
        //去第二家水果摊(上面会被改成下面)
     // GHEFruitStand ghefruitStand =new GHEFruitStand();
     // ghefruitStand.sellFruit("西瓜");
    }
}

Dependency Injection优点:

  1. 低耦合
  2. 可维护性(Maintainability)
  3. 可测试性(Testablility)
  4. 平行开发(Parallel development)

Dependency Injection设计模式

constructor :传入需要依赖的东西,当传入的东西较多,constructor也会越来越大。

public class ABCFruitStand {

    private String fruit;
    public FruitStand(String fruit){
        this.fruit=fruit;
    }
}
public class Customer {

    private FruitStand fruitStand;
    public void buy(){
        fruitStand =new FruitStand("西瓜");
    }
}

setter:比constructor 较为弹性,可以传较多的东西。

public class ABCFruitStand {
    //从外部注入
    private String fruit;
    public void setFruit(String fruit){
        this.fruit=fruit;
    }
}
public class Customer {

    private FruitStand fruitStand;
    public void buy(){
        fruitStand =new FruitStand();
        fruitStand.setFruit("西瓜");
    }
}

interface:只要有继承FruitStand的类别都可以注入。

public interface FruitStand {
    void sellFruit(String fruitName);
}
public class CheapFruitStand implements FruitStand {

    @Override
    public void sellFruit(String fruitName) {

    }
}
public class FreshFruitStand implements FruitStand {
   @Override
    public void sellFruit(String fruitName) {

    }
}

总结:
Dependency Injection是一个好用的方法,对於日後程序的维护可以花费较少的心力。

如果说的有问题欢迎提出。


<<:  JavaScript Day 28. Callback Function ( 回呼函式 )

>>:  Day 22 : 插件篇 01 — 如何在 Obsidian 中快速拆分笔记?使用 Note Refactor 让你弹指之间完成

Day 26: 策略和层级、业务规则 (待改进中... )

「软件系统是策略(Policy)的陈述。电脑程序是将输入转换为输出的『策略的详细陈述』」 「会因着...

[Day 12] Create新增资料

在终端机执行php artisan route:list可以得到 执行create使用GET Met...

Day 28--Complex lifecycle situations

在范例Dessert App中利用timer来观察更复杂的生命周期 Timer 专案中的class ...

Day28:Azure小白如何使用Azure Cache for Redis来存取常用资料

在昨天我们谈完如何使用Azure Kubernetes Service部署Container应用程序...

Day 09 提升关键字的点阅率

在关键字设置完毕後,你可以会透过 Google Ads 去观察每个字的点阅状态,当你觉得明明关键字很...