简单工厂
简单工厂设计模式:包含一组需要创建的对象,通过一个工厂类来实例化对象。
好处:去掉上端对细节的依赖,保证上端的稳定。符合依赖倒置原则(依赖倒置原则:上层模块不应该依赖于下层模块,二者应该通过抽象来依赖。依赖抽象,而不是依赖细节)。
缺陷:没有消除矛盾,只是转移矛盾,甚至还集中了矛盾。
任何设计模式都是解决一类问题的,不是万能的,通常在解决一类问题的时候,还会带来新的问题。
普通写法
通过一个静态方法来判断生成相应的对象。
public class ObjectFactory
{
public static IRace CreateInstance(RaceType raceType)
{
IRace race = null;
switch (raceType)
{
case RaceType.Human:
race = new Human();
break;
case RaceType.NE:
race = new NE();
break;
case RaceType.ORC:
race = new ORC();
break;
case RaceType.Undead:
race = new Undead();
break;
default:
throw new Exception("wrong raceType");
}
return race;
}
}
public enum RaceType
{
Human,
NE,
ORC,
Undead
}
简单工厂+ 配置文件(可配置)
读取配置文件的节点来创建对象。
public class ObjectFactory
{
public static IRace CreateInstance(RaceType raceType)
{
IRace race = null;
switch (raceType)
{
case RaceType.Human:
race = new Human();
break;
case RaceType.NE:
race = new NE();
break;
case RaceType.ORC:
race = new ORC();
break;
case RaceType.Undead:
race = new Undead();
break;
default:
throw new Exception("wrong raceType");
}
return race;
}
private static string IRaceType = ConfigurationManager.AppSettings["IRaceType"];
public static IRace CreateInstanceConfig()
{
RaceType raceType = (RaceType)Enum.Parse(typeof(RaceType), IRaceType);
return CreateInstance(raceType);
}
}
public enum RaceType
{
Human,
NE,
ORC,
Undead
}
配置文件采用App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="IRaceType" value="Human"/>
</appSettings>
</configuration>
此种方式还是依赖new去创建对象。
简单工厂+配置文件+反射(可配置可扩展)
public class ObjectFactory
{
private static string IRaceTypeReflection = ConfigurationManager.AppSettings["IRaceTypeReflection"];
public static IRace CreateInstanceConfigReflection()
{
Assembly assembly = Assembly.Load(IRaceTypeReflection.Split(',')[1]);
Type type = assembly.GetType(IRaceTypeReflection.Split(',')[0]);
return (IRace)Activator.CreateInstance(type);
}
}
public enum RaceType
{
Human,
NE,
ORC,
Undead
}
配置文件采用App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<appSettings>
<add key="IRaceTypeReflection" value="FactoryPattern.War3.Service.Human,FactoryPattern.War3.Service"/>
</appSettings>
</configuration>
此种方式采用反射去创建对象,可以实现子类的动态扩展添加,实现程序的可扩展。
存在的问题
1、可配置后,如果一个接口,可能需要不同的实例,如何实现?
2、目前只是创建IRace对象,就需要一个方法;那项目中有N多个接口,难道每个接口都去创建一个工厂方法吗?
最好的解决方法是采用IOC&DI(控制反转&依赖注入)来实现。——可查看其他博客来学习。