LoginSignup
1
0

More than 3 years have passed since last update.

【Java】Spring DI ②

Posted at

Javaにおける注入って何?

  • インターフェース型の変数に、インスタンスを入れること
  • newしたインスタンスを、そのままEngineインターフェース型の変数に入れる
//Mainクラスでエンジンの生成
Engine hondaEngine1 = new HondaEngine();
Engine mitsubishiEngine1 = new MitsubishiEngine();
//車の生成
Car car1 = new Car(hondaEngine1);
Car car2 = new Car( MitsubishiEngine1);

クラスを変更する

  • 新しくこれまでのエンジンクラスを継承した、Ver2のエンジンを作成した場合
  • Mainクラスの生成部分でで再度Ver2のエンジンに変更する必要がある。。(たくさんあると面倒)
  • →次の章のFactoryクラスを使おう!
//HondaEngine継承したHondaEngineVer2作成
public class HondaEngineVer2 extends HondaEngine{

//コンストラクタ
public HondaEngineVer2(){
    super();
    }
    //エンジン起動
    @Override
    public void boot(){
        System.out.println("ホンダエンジン起動(Ver2)");
    }
    //エンジン停止
    @Override
    public void stop(){
        System.out.println("ホンダエンジン停止(Ver2)");
    }
}
//Mainクラスでエンジンの生成
Engine hondaEngine1 = new HondaEngineVer2();
//車の生成
Car car1 = new Car(hondaEngine1);

Factoryクラス

  • インスタンスを生成するクラスのこと🏭
  • newするクラスが変わった場合、メソッドの中身だけを変えるだけで済む
    • 以下の例ではFactoryクラスでVer2に変更するのみ!
  • 変更に強いアプリケーションになる!!
//Factoryクラス
//メソッドをstaticにすることで、Factoyクラスを生成しなくてもメソッドを呼び出せる
public class EngineFactory{
    //ホンダエンジンクラスを生成して返す
    public static Engine createHondaEngine(){
    //新しいエンジンに変更
        return new HondaEngineVer2();
    }
    //三菱エンジンクラスを生成して返す
    public static Engine createMutsubishiEngine(){
        return new MutsubishiEngine();
    }
}
//mainクラス
public class Main{ 
    public static void main(String[]args){
    //エンジンの生成 
    Engine hondaEngine1 = EngineFactory.createHondaEngine();
    Engine hondaEngine2 = EngineFactory.createHondaEngine();
    Engine mitsubishiEngine1 = EngineFactory.createMutsubishiEngine();
    //車の生成
    Car car1 = new Car(hondaEngine1);
    Car car2 = new Car(hondaEngine2);
    Car car3 = new Car(mutsubishiEngine1);
    }
}
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