Code Monkey home page Code Monkey logo

exercise-dependencyinjection's Introduction

依賴注入定義

  • 在單元測試中,如何讓不可測試的變成可以測試,使用注入方式,讓依賴關係改變成可被測試

舉例情境

賣雨傘晴天9折,雨天無折扣

  1. 測試時產生問題 : 雨傘何時打折須依賴天氣決定
    • 先解決依賴關係,把天氣改成介面後使用注入方式,不要在買雨傘時實作取得天氣狀況,在外部處理,再注入買雨傘方法中
  2. 解除依賴關係後,測試上如何進行呢?
    • 做"假物件"繼承物件實作後代替真Weather傳入,同時假物件要可控制,由假物件實作介面

Manual Injection 的種類

  • Method injection 上述例子就屬此種類,方法注入
  • Constructor injection 建構子時注入,能確保物件在使用時一定都會初始化,也確保不會被修改
  • Property injection 比較少用,屬性公開提供直接修改
  • Ambient context 比較少用,修改環境物件,例如單例模式

library Injection 的種類

Dagger Hilt Koin
Component 程式碼生成利用Annotation,compile後產生檔案 基於Dagger,在Android使用上做簡化 純Kotlin編寫,使用Kotlin語法糖,不使用Annotation和反射機制
學習成本
編譯時間
需撰寫的程式碼量
自動生成程式碼 yes yes no
編譯正確性 yes yes no
Android studio支持 yes yes no

自動生成程式碼

  • Dagger、Hilt 專案越大檔案越大

Android studio支持

  • Dagger、Hilt 在4.1版本IDE有圖標截圖 2024-01-28 下午3 15 35可以點擊查看程式碼間依賴關聯繫的關係

exercise-dependencyinjection's People

Contributors

quuanna avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.