开发者

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). 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.

Do you have a better approach to cope this scenario 开发者_StackOverflow中文版?


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

Sounds like what you want, right?


Microsoft calls this The Provider Model Design Pattern. 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.

  • 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜