我有一個包含視圖依賴關係(所有接口)的類。基本上,類的行爲是通過實現這些接口來定義的。我希望能夠有一個「構建器」,它可以通過接口的不同實現(或其部分)來創建此類的實例。這樣的事情:尋找一種設計模式,可以用不同的接口實現創建一個類的不同實例
public class API
{
private readonly ISomeInterface _someInterface;
private readonly ISomeOtherInterface _someOtherInterface;
private readonly ISomeAnotherInterface _someAnotherInterface;
API(ISomeInterface someInterface,ISomeOtherInterface someOtherInterface,ISomeAnotherInterface someAnotherInterface)
{*/implementation ommitted*/}
//Example method
public void DoSomethingWhichDependsOnOneOrMoreInterfaces()
{
//somecode
id(_someInterface != null)
_someInterface.SomeMethode();
}
public class MyApiBuilder()
{
// implementation ommitted
API CreateAPI(someEnum type)
{
switch(type)
{
case SpecificAPI32:
var speficImplementationOfSomeInterface = new ImplementsISomeInterface();
speficImplementationOfSomeInterface .Setup("someSetup");
var specificImplementationOfOtherInterface = new ImplementsISomeOtherInterface();
returns new API(speficImplementationOfSomeInterface,specificImplementationOfOtherInterface ,null);
}
}
}
什麼是最優雅的方式來實現它(如果這是有道理的)?我首先想到了Builder的設計模式,但據我所知,它略有不同。
[編輯] 正如我指出的那樣,我實施它的方式是一種工廠方法,但我並不完全滿意它。 API可以包含各種不同的接口,這些接口可以完全獨立,但有些可能依賴於其他接口(但不是強制性的)。我想給用戶(開發人員使用這個「API」)儘可能多的自由在創建他想要使用的API。讓我們試着解釋一下我基本上可以達到: 假設我正在開發一個遊戲引擎的插件,它可以將成就和其他內容發佈到各種社交媒體渠道。所以基本上可以有一個接口,它實現了對twitter,facebook,youtube,無論什麼或者一些定製服務器的訪問。這個自定義服務器可能需要某種認證過程。用戶應該能夠在開始時以良好的(hmm fluent is nice ..)方式構建API。所以基本上是這樣的:
var myTotallyForMyNeedsBuildAPI = API.CreateCustomApi().With(Api.Twitter).And(Api.Facebook).And(Api.Youtube).And(Api.CustomServer).With(Security.Authentification);
我實際上不知道如何使流利,但這樣的事情會很好。
你有沒有檢查工廠? –
是的,我檢查了工廠的方法,這基本上是我的例子做對了嗎?但我想我不需要靜態的MyApiBuilder,但我想知道是否有更優雅的方法。 – zlZimon
根據應用程序的規模,您可能需要考慮依賴注入。 –