SOLID の原則によれば、クラスは他のクラスに依存することはできず、依存関係を注入する必要があります。それは簡単です:
class Foo
{
public Foo(IBar bar)
{
this.bar = bar;
}
private IBar bar;
}
interface IBar
{
}
class Bar: IBar
{
}
しかし、IBar の背後にある正確な実装を知らずに、Foo クラスで Bar を作成できるようにしたい場合はどうすればよいでしょうか? ここで 4 つの解決策を考えることができますが、それらにはすべて欠点があるようです。
- オブジェクトのタイプを注入し、リフレクションを使用する
- ジェネリックの使用
- 「Service Locator」を使用して Resolve() メソッドを呼び出します。
- 分離されたファクトリ クラスを作成し、それを Foo に挿入します。
class Foo
{
public void DoSmth(IBarCreator barCreator)
{
var newBar = barCreator.CreateBar();
}
}
interface IBarCreator
{
IBar CreateBar();
}
class BarCreator : IBarCreator
{
public IBar CreateBar()
{
return new Bar();
}
}
最後のケースは当然のようですが、BarCreator クラスのコードが少なすぎます。では、どちらが良いと思いますか?