寻找可以使用不同的接口实现创建类的不同实例的设计模式

时间:2015-10-18 15:42:01

标签: c# design-patterns builder

我有一个包含视图依赖项(所有接口)的类。基本上,类的行为是通过这些接口的实现来定义的。我希望有一个"建设者"它可以使用接口(或其部分)的不同实现来创建此类的实例。像这样:

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 Design Patterns,但据我所知,它略有不同。

[编辑] 正如所指出的,我实现它的方式是工厂方法,但我并不完全满意。 API可以包含各种不同的接口,它们可以完全相互独立,但有些可能依赖于其他接口。(但不是强制性的)我想给用户(开发人员使用这个" API")在创建他想要使用的API时尽可能多的自由。让我们试着解释一下我基本上要做的事情: 让我们说我正在开发一个游戏引擎的插件,可以将成就和其他东西发布到各种社交媒体渠道。所以基本上可以有一个接口,实现对twitter,facebook,youtube,whathever或某些自定义服务器的访问。此自定义服务器可能需要某种身份验证过程。用户应该能够以一种不错的方式(hmm流利的很好......)开始构建API。所以基本上是这样的:

var myTotallyForMyNeedsBuildAPI = API.CreateCustomApi().With(Api.Twitter).And(Api.Facebook).And(Api.Youtube).And(Api.CustomServer).With(Security.Authentification);

我实际上不知道如何使它流利,但这样的事情会很好。

2 个答案:

答案 0 :(得分:1)

您实施的是Factory method模式。

对于您要做的事情来说完全没问题,但您可以根据您的背景以及您对自己的看法来了解其他工厂模式(例如here)代码将在未来发展。

无论如何,我还会考虑不在一个工厂中将这三个接口绑在一起。如果它们真的如此紧密地结合在一起并一起构建,也许它们首先不应该是三个不同的接口,或者至少所有三个接口都是由同一个类实现的,所以你的工厂将用适当的方法构建合适的类。实施这些。

你所追求的可能是Decorator pattern。 在您的API类中,如果已将每个接口提供给API实例,则会调用每个接口,这是Decorator模式的行为。 使用此模式,您可以获得模块化实现,允许您向API添加多个行为。

答案 1 :(得分:1)

使用依赖注入是一种很好的做法,因为您希望程序员能够使用所需的配置组合

检查对这项工作有用的MEFUnity框架。

例如在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撰写并带有所需的实现。