根據SOLID原則,類不能依賴其他類,必須注入依賴關係。這很簡單:依賴倒置。對象創建
class Foo
{
public Foo(IBar bar)
{
this.bar = bar;
}
private IBar bar;
}
interface IBar
{
}
class Bar: IBar
{
}
但是,如果我想我的Foo類能夠創建酒吧,不知道在IBar後面的確切實現? 我能想到的在這裏4級的解決方案,但他們似乎有缺點:
- 注入對象的類型和使用反射
- 使用泛型
- 使用「服務定位器」,並呼籲決心( ) 方法。
- 創建分離工廠類,並將其注入到富:
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類有過痘痘的代碼。 那你怎麼看,哪個最好?
選項4是正確答案:http://stackoverflow.com/questions/1943576/is-there-a-pattern-for-initializing-objects-created-via-a-di-container/1945023#1945023 –
但是,爲什麼你想讓Foo創建IBar?注意泄漏抽象。 –