c# - How to avoid switch-case in a factory method of child classes -


lets have family of classes (cards, sake of it), , need instantiate them based on identifier. factory method this:

public card getcard(int cardnumber)  {    switch(cardnumber)     {      case 13: return new king();      case 12: return new queen();      case 11: return new jack();              }     //... } 

what want avoid switch. why? maybe want reuse comparison in feature.

what came this:

private dictionary<int, type> cardtypes =   {     {13, typeof(king)},    {12, typeof(queen)},    {11, typeof(jack)}  };   public card getcard(int cardnumber)   {             var cardtype = cardtypes[cardnumber];     var instance = activator.createinstance(cardtype);     return (card)instance;  } 

however, solution uses reflection expensive, , problematic when have more 1 "identifier" (for example 1 , 14 both give ace - should add 2 keys dictionary?).

what's best practice in scenario?

instead of storing type in dictionary, store func<card>:

private dictionary<int, func<card>> cardfactories =  {     { 13, () => new king() },     // etc }  public card getcard(int cardnumber)  {             var factory = cardfactories[cardnumber];     return factory(); } 

in case of cards, i'd make them immutable start , populate dictionary cards themselves, that's different matter :)


Comments

Popular posts from this blog

javascript - how to protect a flash video from refresh? -

visual studio 2010 - Connect to informix database windows form application -

android - Associate same looper with different threads -