.net设计模式-简单工厂

简单工厂设计模式:创建型设计模式

将对象的创建交给其它类,自己只关注抽象

1.根据不同的传入参数创建不同的实现对象

 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 ORC();
14                     break;
15                 case RaceType.NE:
16                     iRace = new NE();
17                     break;
18 
19                 //增加一个分支
20                 default:
21                     throw new Exception("wrong raceType");
22             }
23             return iRace;
24         }

2.把传递的参数 放入到配置文件 ,使对象的创建变成可配置的,不用修改代码,只要改动配置文件就行

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.利用反射+配置文件,使对象的创建变成可配置+可扩展(想要增加实现直接粘贴一个dll进去即可)

 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         }

猜你喜欢

转载自www.cnblogs.com/Spinoza/p/11432568.html