Lets say we have a family of classes (cards, for the sake of it), and we need to instantiate them based on some identifier. A factory method would look like this:
Instead of storing the type in the dictionary, you could store a Func<Card>
:
private Dictionary<int, Func<Card>> cardFactories =
{
{ 13, () => new King() },
// etc
}
public Card GetCard(int cardNumber)
{
var factory = cardFactories[cardNumber];
return factory();
}
In the case of cards, I'd probably make them immutable to start with and just populate the dictionary with the cards themselves, but that's a different matter :)