c# - Create Instance of children using "key" -


i have base class "games", , children clases every game, methods making specific action every game, functions generic. make games class abstract, , every children implements abstract method or using base clase generic method. every children have same functions, implements diferent in cases. (i think correct way)

using system.io; using system;  namespace appgames {      public abstract class games      {          protected string name;          public games(string name)  // constructor         {              this.name = name;         }          public abstract void show();  // abstract show method      }      public class gamewow: games     {          public gamewow(string name) : base(name) {}  // constructor          public override void show()  //override abstract show method         {             system.console.writeline("name w : " + name);         }     }      public class gamegw2: games     {          public gamegw2(string name) : base(name) {}  // constructor          public override void show()  //override abstract show method         {             system.console.writeline("name g : " + name);         }     }  } 

my problem create instance of every children in correct case, because need call childrens function when 1 webservice pass "key" (not class name)

im using switch, dont know how create "generic" instance of correct children , call funcion later.

update clarify:

i need call times, dont duplicate instances, if call gamewow times, use 1 copy:

 switch (game) {              case "wow":                 classname = "gamewow";             break;              case "gw2":                 classname = "gamegw2";             break;              default:                 classname = null;             break;          }          if (classname != null) {           // create instance of classname           // if exists, use it, if not, create new         } 

thanks.

here's nice clean way using lazy<games>:

public class gamecenter {     private dictionary<string, lazy<games>> games = new dictionary<string, lazy<games>>()     {         { "gamewow", new lazy<games>(() => new gamewow("wow")) },         { "gamegw2", new lazy<games>(() => new gamegw2("gw2")) },     };      public games getgamefor(string gametype)     {         return games.containskey(gametype) ? games[gametype].value : null;     } } 

Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -