mercredi 18 avril 2018

Right way to choose and instantiate C# class depends on string value?

I have base class

public abstract class HostBehavior : SiteHost
{
    public abstract List<string> ParseNews(string url);
}

And many derived classes...

What is the best way to choose which constructor should be called depends on url?

Right now I have long sequence of "if else" statements like this example:

public static HostBehavior ResolveHost(string url)
{
    if (uri.IndexOf("stackoverflow.com") > 0)
    {
        return new stackoverflowBehavior();
    }
    else if(uri.IndexOf("google.com") > 0)
    {
        return new googleBehavior();
    }
    // and so on...
    else
    {
        throw new Exception...
    }
}

Aucun commentaire:

Enregistrer un commentaire