Design pattern for multiples APIs that do the same function

anti-patternsdesign-patternspatterns-and-practices

I retrieve some pieces of information from four forecasting APIs, I have three main methods that I will implement in each API's manager:

  • history (only one of them provides this function)
  • forecasting (all of them)
  • yesterday data (only two)

I am thinking about the following pattern (it's similar to facada/strategy)

enter image description here

Questions:

1) Does this pattern have a name?
2) I want to manage those three methods from a particular class (PARENT API) and I want to find the easiest way to add a new API in the future. What is the pattern that fits better in this case?

Best Answer

I am not sure of the pattern name, but a possible scenario is that you will need multiple interfaces to support what has been shown. Each API will choose what interfaces to implement. The manager implements all interfaces and will automatically handle whether or not the current forecaster can perform the desired operation.

So adding more APIs should be straight forward as each API can pick and choose what interfaces to support. All operations are handled in the manager.

Interfaces

 public interface IForcastable
 {
     void Forecast();
 }

 public interface IHistoricalForcastable 
 {
     void ForecastHistory();
 }

 public interface IPreviousDayForcastable 
 {
     void ForecastYesterday();
 }

APIs

public class Api1 : IForcastable, IPreviousDayForcastable
{
    public void Forecast()
    {
        //Implement Here
    }

    public void ForecastYesterday()
    {
        //Implement Here
    }
}

public class Api2 : IForcastable, IHistoricalForcastable
{
    public void Forecast()
    {
        //Implement Here
    }

    public void ForecastHistory()
    {
        //Implement Here
    }
}

Finally the Manager will implement everything and handle whether or not the current forecaster being managed can perform the operation.

Manager API

public class ForecastApiManager: IForcastable, IHistoricalForcastable, IPreviousDayForcastable
{
    private readonly IForcastable _forcaster;

    public ForecastApiManager(IForcastable forcaster)
    {
        _forcaster = forcaster;
    }


    public void ForecastHistory()
    {
        var historicalForcaster = _forcaster as IHistoricalForcastable;

        if (historicalForcaster != null)
        {
            historicalForcaster.ForecastHistory();
        }
    }

    public void ForecastYesterday()
    {
        var yesterdayForecaster = _forcaster as IPreviousDayForcastable;

        if (yesterdayForecaster != null)
        {
            yesterdayForecaster.ForecastYesterday();
        }
    }

    public void Forecast()
    {
        _forcaster.Forecast();
    }


}
Related Topic