简体   繁体   English

这有设计模式吗?

[英]Is there a design pattern for this?

I have a component that needs to call a specific service depending on the input it receives. 我有一个组件,需要根据它收到的输入调用特定的服务。 So my component has to look at the input and based on a configuration that says "for this input call this service with this data" needs to call the proper service. 因此,我的组件必须查看输入并基于一个配置,该配置说“对于此输入调用,此服务与此数据”需要调用正确的服务。 The services have a common signature method and a specific one (each). 这些服务具有共同的签名方法和特定的签名方法(每个)。

I thought about an abstract class that includes the signatures for all three methods. 我想到了一个包含所有三种方法签名的抽象类。 The implementation for the two services will override all three methods (throwing NotImplementedException for the methods that are not supported by current service). 两个服务的实现将覆盖所有三个方法(为当前服务不支持的方法抛出NotImplementedException )。 A component that could be initialized with a map (that for each input type will have the type of the service to be called) will also be defined. 可以使用map初始化的组件(每个输入类型将具有要调用的服务的类型)也将被定义。

Do you have a better approach to cope this scenario ? 你有更好的方法来应对这种情况吗?

Factory pattern has this definition: 工厂模式有这个定义:

Define an interface for creating an object, but let subclasses decide which class to instantiate. 定义用于创建对象的接口,但让子类决定实例化哪个类。 Factory Method lets a class defer instantiation to subclasses Factory Method允许类将实例化延迟到子类

Sounds like what you want, right? 听起来像你想要的,对吧?

Microsoft calls this The Provider Model Design Pattern . Microsoft称之为提供者模型设计模式 Although since your methods do not implement all methods perhaps it isn't a great fit. 虽然你的方法没有实现所有方法,但它可能并不合适。

At its most basic level the pattern is: 在最基本的层面上,模式是:

  • An abstract base class defining a contract. 定义合同的抽象基类。 The abstract base class has all the abstract methods and properties required to implement the public API it supports. 抽象基类具有实现它支持的公共API所需的所有抽象方法和属性。

  • Configuration information. 配置信息。 Once an implementation of the feature provider class is created, it must be described in the configuration section. 一旦创建了功能提供程序类的实现,就必须在配置部分中对其进行描述。 The description of the provider within configuration provides all the information so that the provider can be instantiated in the running application. 配置中的提供程序的描述提供了所有信息,以便可以在正在运行的应用程序中实例化提供程序。

The abstract base class usually should support factory methods to create new objects. 抽象基类通常应该支持工厂方法来创建新对象。

The Strategy design pattern is well suited for your problem. 策略设计模式非常适合您的问题。 A strategy encapsulates an algorithm and that needs to be executed depending on the type of data you have as input. 策略封装了一个算法,需要根据您输入的数据类型执行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM