mardi 18 août 2020

Resolving interfaces at runtime (just before the usage)

Lets say i have the following interface

interface ILeague
{
    string ShowSquad();
}

Following classes implementing them

class EPL : ILeague
{
    public string ShowSquad()
    {
      return "EPL players collection";
    }
} 

class LaLiga: ILeague
{
  public string ShowSquad()
  {
     return "La-liga player Collection";
  }
}

i am consuming this interface as shown below

public string ShowLeaguePlayers(ILeague leagueDataProvider)
{
   return leagueDataProvider.ShowSquad();
}

Now , depending on the league i am in , i want to show different data. Sometimes EPL and other times LaLiag. This switch can happen with in the same execution cycle. I tried the following approach

class LeagueDataProvider : ILeague
{
    private ILeague m_Provider;

    private string league;
    private void SetContext()
    {
        // Have some logic to figure out the league
        league = "EPL";

        if (league.Equals("EPL"))
        {
            m_Provider = new EPL();
        }
        else
        {
            m_Provider = new LaLiga();
        }
    }

    public string ShowSquad()
    {
        SetContext();
        return m_Provider.ShowSquad();
    }
}

I have modified my client code to below

void ShowData()
{
   ILeague Dataprovider = new LeagueDataProvider();
   Console.WriteLine(ShowLeaguePlayers(Dataprovider));             
}
 
// copied again for easy viewing
public string ShowLeaguePlayers(ILeague leagueDataProvider)
{
   return leagueDataProvider.ShowSquad();
}

This works fine , but every time i make a call to ShowSquad , it has to check for the league and fetch the data. Is there a better way to do this ?

What i am trying to achieve here :

Depending on the league , i want to get different data when i call ShowSquad . I should be able to mock ILeague in UT and in future there might be many more implementations of ILeague so i want to avoid modifying and re-testing components which consume them

Aucun commentaire:

Enregistrer un commentaire