jeudi 28 février 2019

Design question regarding Factory Pattern

I want to inject a type IGameScoreSource into a class but I'm stumped how to go about it.

static class GamesScoreSourceFactory
{
    public IGameScoreSource GetGameScoreSource(GameScoreSourceType gameScoreSourceType)
    {
        switch(gameScoreSourceType)
        {
            case FromFile:
                return new GameScoreFile();
            case FromDB:
                return new DatabaseRepos();
            case FromThirdPartyAPI:
                return new ThirdPartyWrapper();
        }   
    }
}

I have two questions for two different scenarios.

All three cases magically figure out where to source the parameters. So for GameScoreFile it knows what file path to look at, for DatabaseRepos it knows where to find the connection string.

Presumably, these locations are hard-coded in the concrete classes. But what if I wanted to change the locations? Assuming scores.txt was hard coded what if instead I wanted rand_scores.txt?

So:

 static class GamesScoreSourceFactory
    {
        public IGameScoreSource GetGameScoreSource(GameScoreSourceType gameScoreSourceType, string param)
        {
            switch(gameScoreSourceType)
            {
                case FromFile:
                    return new GameScoreFile(string param);
                case FromDB:
                    return new DatabaseRepos(string param);
                case FromThirdPartyAPI:
                    return new ThirdPartyWrapper(ThirdPartyConfig conf{IPAddress = ipAddress, Port = port});
            }   
        }
    }

The first two cases were fine but the third case doesn't because it takes a config object.

Do I have to create another factory class? But won't the calling code have to know which Factory object to invoke, and as result becomes a Factory in itself?

I'm not sure how to handle this... If this is a duplicate please link me.

Aucun commentaire:

Enregistrer un commentaire