namespace ReflectionFactory_DesignPattern
{
using System;
using System.Reflection;
//基类是交通工具Vehicle类
public abstract class Vehicle
{
public abstract string Go();
}
//这里,由Vehicle类派生出2个子类
public class Car : Vehicle
{
public override string Go()
{
return "汽车飞驰";
}
}
public class Boat : Vehicle
{
public override string Go()
{
return "轮船排水";
}
}
//仔细看这里的代码,利用了.NET平台的反射技术,使简单工厂类的设计更简约和可扩展
public class VehicleSimpleFactory
{
public static Vehicle Create(string typename)
{
//获取传递进来的类名的类型(包含名称空间,如myspace.myclass),区分大小写,找不到时,抛出异常
Type type = Type.GetType(typename, true);
object objInstance = Activator.CreateInstance(type);
return (Vehicle)objInstance;
}
}
//这里,我我们扩展一个由Vehicle派生的新的子类:Train时,我们不需要对VehicleSimpleFactory类
//内部的Create方法做修改,这就是使用反射技术的好处了
public class Train : Vehicle
{
public override string Go()
{
return "火车冒烟";
}
}
class Client
{
static void Main()
{
Vehicle v = VehicleSimpleFactory.Create("ReflectionFactory_DesignPattern.Boat");
Console.WriteLine( v.Go());
v = VehicleSimpleFactory.Create("ReflectionFactory_DesignPattern.Car");
Console.WriteLine(v.Go());
//扩展的Train类使用
v = VehicleSimpleFactory.Create("ReflectionFactory_DesignPattern.Train");
Console.WriteLine(v.Go());
Console.Read();
}
}
}
//在简单工厂模式中使用反射技术的好处是显而易见的,我们在扩展Vehicle的子类时,在Vehicle的工厂类
//VehicleSimpleFactory中不需要做任何的改动。
使用反射技术的代价是工厂与产品之间的依赖关系不明显,由于是动态绑定,因此理论上可以用一个工厂完成很多类型的实例化,从而使代码不容易理解.另外增大了测试难度,创建是动态完成的,测试用例的编写和测试执行要比传统的工厂困难.
2163



被折叠的 条评论
为什么被折叠?



