Search code examples
c#factory-pattern

How does this model factory know which method to use?


I am running through a tutorial and I understand what is being taught and the sample code works as described. But I am missing one piece to the puzzle and that is how the factory knows which "create" to use....so I guess I don't understand everything being taught.

In trying to research I came across this article but it didn't answer my "how does it know" question as their situation is slightly different.

The _modelFactory.Create(f) is what is confusing me.

Here is the code that is executing

_modelFactory = new ModelFactory();
...snip....


public IEnumerable<FoodModel> Get(bool includeMeasures = true)
{
  IQueryable<Food> query;

  if (includeMeasures)
  { query = _repo.GetAllFoodsWithMeasures(); }
  else
  { query = _repo.GetAllFoods(); }

  var results = query.OrderBy(f => f.Description).Select(f => _modelFactory.Create(f));

  return results;
}

In the model factory there are two creates

public class ModelFactory
{
   public FoodModel Create(Food food)
   {
     return new FoodModel()
     { ... };
   }

   public MeasureModel Create(Measure measure)
   {
      return new MeasureModel()
      { ... };
   }
}

Is there some implicit association because "query" is of type Food and the modelFactory says ohhh I'll use the FoodModel because that is the entity representation of food?


Solution

  • In this line:

    var results = query.OrderBy(f => f.Description).Select(f => _modelFactory.Create(f));
    

    the f variable is of type Food, since it's coming from an IQueryable<Food> instance. So the Create(Food food) overload is the one being called.

    Really no magic involved, just standard member overloading and overload selection based on type matching of the arguments- read this article for an explanation of how overloading works and how you should use it/design for it.