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?

【SOLID原則⑤】依存性(関係)逆転の原則(DIP)🔁 〜「誰に頼むか」ではなく「何をしてもらうか」〜

0
Last updated at Posted at 2026-01-20

1. 🧠 依存性逆転の原則ってなに?

依存性逆転の原則(DIP)を
初心者向けに一言で言うと 👇

「相手の中身ではなく、役割に頼ろう」

プログラミングに限らず、
日常生活でもよくある考え方です ☺️

2. 🍔 日常例で考えてみよう

❌ ダメな例:特定のお店に依存している

class Person {
  eat() {
    const burgerShop = new McDonalds();
    burgerShop.buyBurger();
  }
}

class McDonalds {
  buyBurger() {
    console.log("マクドナルドのハンバーガーを食べる");
  }
}

何が困る?🤔

マクドナルドしか行けない

モスバーガーに行きたくなったら?
→ Personを書き換える必要がある 😱

👉 「どこで買うか」まで決めつけているのが問題です。

✅ 考え方を変えてみよう

人が本当に求めているのは👇

「ハンバーガーが食べたい」🍔

であって、

「マクドナルドである必要」 はありません。

🔑 ポイント:まず「約束」を作る

interface BurgerShop {
  buyBurger(): void;
}

👉
これは

「ハンバーガーを売ってくれるお店」

という 役割(約束) です。

🍟 お店側は約束を守るだけ

class McDonalds implements BurgerShop {
  buyBurger() {
    console.log("マクドナルドのハンバーガーを食べる");
  }
}

class MosBurger implements BurgerShop {
  buyBurger() {
    console.log("モスバーガーのハンバーガーを食べる");
  }
}

🧍 人は 「お店の種類」 を気にしない

class Person {
  constructor(private shop: BurgerShop) {}

  eat() {
    this.shop.buyBurger();
  }
}

👉
Personは

  • マクドナルドか?

  • モスバーガーか?

一切知らない のがポイントです ✨

🔄 差し替えが簡単!

  • モスバーガーを食べる
const shop = new MosBurger();
const person = new Person(shop);
person.eat();

👇 別の日には

  • マクドナルドを食べる
const shop = new McDonalds();
const person = new Person(shop);
person.eat();

👉 Personは変更ゼロ! 🎉

3. 🔁 なぜ「依存性逆転」なの?

普通は👇

  • Person(使う側)
  • McDonalds(使われる側)

に依存します。

でもDIPでは👇

  • Person も

  • McDonalds も

👉 BurgerShop(約束)依存しています。

これによって
依存の向きが逆転している ように見えるんですね 🔄

4. 🧪 初心者向けチェックポイント

こんなコードを書いていたら要注意 🚨

new McDonalds()

クラスの中で
特定のものを決め打ちしていたら 👀

👉「これ、役割にできないかな?」
と一度考えてみましょう 💡

5. 🌱 実務につながる話(超かんたん)

  • React
    → APIの中身を知らずに使える

  • Django
    → DBの種類を意識せずに処理できる

これらも DIPの考え方がベース になっています。

6. 🏁 おわりに

依存性逆転の原則は
SOLIDの中でも 一番抽象的 です。

でも👇

「人は店に依存しない。ハンバーガーに依存する」🍔

このイメージを覚えておけばOKです 😊

設計は
最初から完璧にやらなくて大丈夫。

「変更しづらくなってきたな…」
と感じたときに
DIP を思い出してみてください 🔁✨

次回はSOLID原則シリーズのまとめをお送りします。

最後まで読んでいただきありがとうございました!🎉

よろしければ他の記事もご覧頂けるとすごくうれしいです。

👍 いいね / 💬 コメントいただけると励みになります!

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?