本記事は Dart で記載しています。https://dartpad.dev/

DI: Dependency injection

In software engineering, dependency injection is a technique in which an object receives other objects that it depends on, called dependencies.

Dependency injection - Wikipedia

あるオブジェクトが、自分が依存する別のオブジェクトを受け取ること。

DI していない例

void main() {
  CyberDuck().cry();
}

class Computer {
  String calc() {
    return '42';
  }
}

class CyberDuck {
  final Computer _computer = Computer();

  void cry() {
    print('GaGa!');
    final String answer = _computer.calc();
    print('Answer to the Ultimate Question of Life, the Universe, and Everything is ... $answer');
  }
}

コンストラクタインジェクションの例

void main() {
  CyberDuck(Computer()).cry();
}

class Computer {
  String calc() {
    return '42';
  }
}

class CyberDuck {
  final Computer _computer;

  CyberDuck(this._computer);

  void cry() {
    print('GaGa!');
    final String answer = _computer.calc();
    print('Answer to the Ultimate Question of Life, the Universe, and Everything is ... $answer');
  }
}

セッターインジェクションの例

void main() {
  var cyberDuck = CyberDuck();
  cyberDuck.computer = Computer();
  cyberDuck.cry();
}

class Computer {
  String calc() {
    return '42';
  }
}

class CyberDuck {
  Computer? _computer;

  set computer(Computer computer) {
    _computer = computer;
  }

  void cry() {
    print('GaGa!');
    final String answer = _computer!.calc();
    print('Answer to the Ultimate Question of Life, the Universe, and Everything is ... $answer');
  }
}

メソッドインジェクションの例

void main() {
  CyberDuck().cry(Computer());
}

class Computer {
  String calc() {
    return '42';
  }
}

class CyberDuck {
  void cry(Computer computer) {
    print('GaGa!');
    final String answer = computer.calc();
    print('Answer to the Ultimate Question of Life, the Universe, and Everything is ... $answer');
  }
}

おわり

コンストラクタインジェクションを使いましょう。