2010-08-10 66 views
0

哪種方法爲抽象工廠方法提供值?根據IoC和抽象工廠模式的類設計

例如,

interface IFactory 
{ 
    ISomething Create(int runTimeValue); 
} 

class Factory : IFactory 
{ 
    public ISomething Create(int runTimeValue) 
    { 
    return new Something(repository, runTimeValue); 
    } 
} 

在這個例子庫通過構造函數注入創建廠當,但我可以代替移動存儲庫IFactory接口

interface IFactory 
{ 
    ISomething Create(IRepository repository, int runTimeValue); 
} 

class Factory : IFactory 
{ 
    public ISomething Create(IRepository repository, int runTimeValue) 
    { 
    return new Something(repository, runTimeValue); 
    } 
} 

什麼被認爲是這樣做的「正確」的方式? 設計一個抽象工廠應該如何一個原因?

回答

0

Abstract Factory pattern應該用於工廠返回的對象需要以不同的方式「初始化」,只有工廠知道如何去做。因此,不同的ISomething實現將被「初始化」或創建不同,並且只有它們各自的Factory實現方法才知道如何執行它。

你的情況,你要問自己:

ISomethings的所有實現需要的IRepository以及runtimeValue?在這種情況下,您可以使用工廠模式。

使用抽象工廠在這樣的場景:(有什麼和SomeOtherthing是不同創建)

interface IFactory { 
    ISomething Create(int runTimeValue); 
} 

class Factory : IFactory { 
    public ISomething Create(int runTimeValue) { 
    return new Something(repository, runTimeValue); 
    } 
} 

class OFactory : IFactory { 
    public ISomething Create(int runTimeValue) { 
    // constructor takes different parameters 
    SomeOtherthing thing = new SomeOtherthing("someValue", runtimeValue); 
    thing.SetCustomRepository(new OtherRepositoryImpl()); 
    return thing; 
    } 
} 
+0

謝謝,這有助於:) – Marcus 2010-08-10 16:55:59

+0

你將如何測試這家工廠? OtherRepositoryImpl是一個具體的實現.... – danidacar 2014-08-12 12:49:38

0

我會說是一致的。如果您的資源庫被注入到其他地方,那麼將其注入到工廠的構造函數中而不是將其作爲界面的一部分是有意義的。