What design is best for loading different classes of the same type based on only aliases available?

StackOverflow https://stackoverflow.com/questions/23520133

  •  17-07-2023
  •  | 
  •  

Pergunta

I'm doing a small engine that migrates content from one project to another, and the system it uses the content from is split into small modules.

I have a modules selection that should transfer their content into another project.

What design fits better here? I only have module names from the user input, like: Content, Navigation, Boxes, Payments, etc...

I was thinking of Factory, but it seems a bit wrong. Maybe Strategy?

Basically, I have a bunch of classes, they all share the same interface, but implement it differently because each module have different SQL tables to grab the content from and how it parses it out to the user.

Appreciate any help.

Foi útil?

Solução

If I understand your question correctly, the answer is both Factory and Strategy. The Strategy object knows how to work with a particular data source and the Factory knows which Strategy object to give you based on the alias provided.

var dataStrategy = dataFactory.GetStrategyByAlias(alias);
dataStrategy.Insert(data);

Your concrete Strategy classes can override an Alias property to assist the Factory like so:

interface IDataStrategy {
    string Alias { get; }
    void Insert(MyDataClass data); 
}

class ConcreteStrategy : IDataStrategy{
    string Alias { 
       get{
           return "Some Data source alias";
       }
    }     
}

class DataFactory{
    private IDataStrategy[] _strategies;

    public IDataStrategy GetStrategyByAlias(string alias){
        return _strategies.FirstOrDefault(x => x.Alias == alias);
    }
}

If the consuming object has a ready list of the strategies then the Factory may be overkill as it could just execute the same Linq statement.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top