0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

DI(Dependency Injection)に使われる「依存性」とは?

Posted at

DI(Dependency Injection)とは

  • 依存性の注入 or オブジェクトの注入
  • spring frameworkの「コア」となっている
  • クラス間での依存関係を減らし、外部からいれる(注入する)ようにするデザインパターンの一つ

メリット

  • 依存性が少ないため、コードの書き換えがしやすい( == 変化に強い)
  • 依存性が少ないため、単体テストがしやすい
  • クラス別でやり方を決めるため、変える場所がわかりやすい

依存性って何?(疑問)

  • 相手が変更されたときにうける影響
  • クラスとクラスの関係性・結びつき

依存性が強い

qiita.kt

class AttackMethod(){
    fun attackhand(): String{ 
        return "素手で攻撃しました" // 返り値が「文字列」の型で返す
    }
}

class Player(){ 
    fun playerAttack(): String{ // 
        val a = AttackMethod() // AttackMethodクラスをa変数に代入
        return a.attackhand() // attackhand関数を呼び出す
    }
}


fun main(args:Array<String>){
    println("プレイヤーが攻撃します")
    val player = Player() // Playerクラスをplayer変数に代入
    println(player.playerAttack()) //playerAttack関数を呼ぶ
    
}

**「依存性が強い」**と呼ばれる箇所は

Playerクラス と AttackMethodクラス

理由: 目的のクラスを変更するときに、他のクラスから修正しないといけない!!

qiita.kt

class AttackMethod(){
    fun attackhand(): String{ 
        return "素手で攻撃しました" // 返り値が「文字列」の型で返す
    }
}

class Player(){ 
    fun playerAttack(): String{ // 
        val a = AttackMethod() // AttackMethodクラスをa変数に代入
        return a.attackhand() // attackhand関数を呼び出す
    }
}

例えば・・・・

  1. 「やっぱり、Playerクラスでは、"素手"と"ダメージ量"も返したい。

  2. そうすると、playerAttack関数の返り値を変更しないといけないな。

  3. けど、AttackMethodクラス内のattackhand関数を変更しないと作業ができないぞ・・・・

Playerクラス内で、AttackMethodクラスのインスタンスを使いたい場合は、AttackMethodクラスが使えるような状態にしておく必要がある。
つまり、PlayerクラスはAttackMehodクラスに依存していると言える!!(かな・・・・)

まとめ

「DI」の日本語での意味は、「依存性の注入 or オブジェクトの注入」。
「依存性」とは、クラスとクラス間の関係性のこと。

「依存性が強い」とは、あるAクラスでBクラスのインスタンスを使用したいときに、Bクラスの実装が終えないとAクラスが使えない状態・Bクラスを修正しないといけないということ

「依存性の注入」の「依存性」とは、処理を分散・使いやすくするために、クラス間の依存関係をなるべく減らすようにしようという意味

※「依存性」についての理解をコードで表してみました。間違い・疑問点があれば、ご指摘ください。

参考リンク(ありがとうございます!!)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?