1
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 1 year has passed since last update.

セッターインジェクションについて

Posted at

セッターインジェクションとは

セッターインジェクションとは、依存オブジェクトをクラスのセッターメソッドを使用して注入する手法です。これは、コンストラクタインジェクションとは対照的に、オブジェクトのインスタンス化の後でも依存性を変更または追加できるメリットがあります。

なぜセッターインジェクションなのか

柔軟性: すでにインスタンス化されたオブジェクトの依存性を変更できます。
オプショナルな依存: すべての依存関係を必須にする必要はありません。一部の依存関係はオプショナルとして扱うことができます。

実装例

Pythonを使用した簡単な例を以下に示します。

class Engine:
    def start(self):
        return "Engine started!"

class Car:
    def __init__(self):
        self._engine = None

    # セッターを使用してエンジンを注入
    def set_engine(self, engine):
        self._engine = engine

    def start(self):
        return self._engine.start()

この例では、CarクラスがEngineクラスの依存関係を持っていますが、セッターメソッドset_engineを使用して注入します。

いつセッターインジェクションを使用するべきか

セッターインジェクションは以下の場合に特に有用です。

  • 依存性がオプショナルである場合。
  • ランタイム中に依存性を変更する必要がある場合。

ランタイム中に依存性を変更する場合とは?

「ランタイム中に依存性を変更する」とは、アプリケーションが実行中(ランタイム中)であっても、オブジェクトの依存関係や機能を動的に変更または置き換えることを指します。

シナリオ
ある車のソフトウェアシステムがあり、この車にはいくつかの異なるエンジンタイプが搭載されています(ガソリン、ディーゼル、電気)。このシステムの目的は、適切なエンジンタイプに基づいてエンジンの動作を制御することです。

車が起動したときには、ガソリンエンジンがデフォルトで搭載されています。しかし、運転手がシステムに介入してエンジンのタイプを変更することができるようにしたい場合(例えば、都市部では電気エンジンに切り替えるなど)、ランタイム中にこの依存性(ここではエンジンの種類)を変更する必要があります。

実装例

class Engine:
    def start(self):
        pass

class GasolineEngine(Engine):
    def start(self):
        return "Gasoline Engine started!"

class ElectricEngine(Engine):
    def start(self):
        return "Electric Engine started!"

class Car:
    def __init__(self):
        self._engine = GasolineEngine()

    def set_engine(self, engine):
        self._engine = engine

    def start_engine(self):
        return self._engine.start()

このシステムでは、set_engineメソッドを使用して、ランタイム中に車のエンジンの種類を動的に変更することができます。

Copy code
car = Car()
print(car.start_engine())  # "Gasoline Engine started!"

# ランタイム中にエンジンの種類を電気エンジンに変更
car.set_engine(ElectricEngine())
print(car.start_engine())  # "Electric Engine started!"
1
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
1
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?