Simple factory design pattern: create design patterns
The other classes to create objects, only focus on the abstract
1. Create an object that implements different depending on the incoming parameters
1 public static IRace CreateRace(RaceType raceType) 2 { 3 IRace iRace = null; 4 switch (raceType) 5 { 6 case RaceType.Human: 7 iRace = new Human(); 8 break; 9 case RaceType.Undead: 10 iRace = new Undead(); 11 break; 12 case RaceType.ORC: 13 iRace = new new the ORC (); 14 BREAK ; 15 Case RaceType.NE: 16 Irace = new new NE (); . 17 BREAK ; 18 is . 19 // add a branch 20 is default : 21 is the throw new new Exception ( " Wrong raceType " ); 22 is } 23 is return Irace; 24 }
2. The parameters passed to the configuration file into the created objects become configurable, without modifying the code, as long as the changes to the configuration file on the line
1 private static string IRacTypeConfig = ConfigurationManager.AppSettings["IRacTypeConfig"];//IRacTypeConfig+参数 2 public static IRace CreateRaceConfig() 3 { 4 RaceType raceType = (RaceType)Enum.Parse(typeof(RaceType), IRacTypeConfig); 5 return CreateRace(raceType); 6 }
3. Use reflection + configuration file, create an object into the configurable + extensible (want to increase direct pasting into a dll can)
1 private static string IRacTypeConfigReflection = ConfigurationManager.AppSettings["IRacTypeConfigReflection"]; 2 private static string DllName = IRacTypeConfigReflection.Split(',')[1]; 3 private static string TypeName = IRacTypeConfigReflection.Split(',')[0]; 4 /// <summary> 5 /// ioc的雏形 可配置可扩展的 6 /// </summary> 7 /// <returns></returns> 8 public static IRace CreateRaceConfigReflection() 9 { 10 Assembly assembly = Assembly.Load(DllName); 11 Type type = assembly.GetType(TypeName); 12 IRace iRace = Activator.CreateInstance(type) as IRace; 13 14 return iRace; 15 }