我有一个包含视图依赖项(所有接口)的类。基本上,类的行为是通过实现这些接口来定义的。我希望能够有一个“生成器”,它可以使用不同的接口(或部分接口)实现来创建此类的实例。像这样的东西:
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,任何人或某些自定义服务器的访问。此自定义服务器可能需要某种身份验证过程。用户应该能够在启动时以一种很好的方式构建API(嗯,流利的很好。)。
var myTotallyForMyNeedsBuildAPI = API.CreateCustomApi().With(Api.Twitter).And(Api.Facebook).And(Api.Youtube).And(Api.CustomServer).With(Security.Authentification);
我实际上不知道如何使它流利,但是像这样的东西会很好。
最好使用依赖注入,这是为了使程序员能够使用所需的配置来组合对象。
检查MEF
和Unity
框架非常适合此工作。
例如,Unity
您可以这样编写:
// Introducing an implementation for ISomeInterface
container.Register<ISomeInterface, SomeImplementation>();
// Introducing an implementation for ISomeOtherInterface
container.Register<ISomeOtherInterface, SomeOtherImplementation>();
// Introducing an implementation for ISomeAnotherInterface
container.Register<ISomeAnotherInterface, SomeAnotherImplemenation>();
container.Register<API, API>();
// and finally unity will compose it for you with desired configurations:
var api = container.Resolve<API>();
在这种情况下,api
将由所需的实现组成。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句