反射工厂模式

[注:摘自http://www.cnblogs.com/hg98/archive/2007/06/06/774338.html]

反射工厂模式: 其实就是通过反射的方式来获得具体实例化是那个类。

1 namespace ReflactionFactoryPartern
2 {
3 public interface IFactoryVehicle
4 {
5 IVehicle CreateVehicle();
6 }
7 }
1 namespace ReflactionFactoryPartern
2 {
3 public class FactoryCar : IFactoryVehicle
4 {
5 public IVehicle CreateVehicle()
6 {
7 return new Car();
8 }
9 }
10 }
1 namespace ReflactionFactoryPartern
2 {
3 public class FactoryBoat : IFactoryVehicle
4 {
5 public IVehicle CreateVehicle()
6 {
7 return new Boat();
8 }
9 }
10 }
1 namespace ReflactionFactoryPartern
2 {
3 public interface IVehicle
4 {
5 void go();
6 }
7 }
1 namespace ReflactionFactoryPartern
2 {
3 public class Car : IVehicle
4 {
5 public void go()
6 {
7 Console.WriteLine("This is a Car");
8 }
9 }
10 }
1 namespace ReflactionFactoryPartern
2 {
3 public class Boat : IVehicle
4 {
5 public void go()
6 {
7 Console.WriteLine("This is a boat.");
8 }
9 }
10 } 

1 using System.Reflection;
2
3  namespace ReflactionFactoryPartern
4 {
5 class ReflectFactory
6 {
7 public static IVehicle CreateVehicleByReflect(string typeName)
8 {
9 string namespaceStr = "ReflactionFactoryPartern";
10 string tempChar = ".";
11 //注意使用Type.GetType(String classname)时,必须指定其命名空间,否则返回为null
12   Type type = Type.GetType(namespaceStr + tempChar + typeName,true);
13
14 ConstructorInfo ci = type.GetConstructor(System.Type.EmptyTypes);
15 return (IVehicle)ci.Invoke(null);
16 }
17 }
18 }

 

1 namespace ReflactionFactoryPartern
2 {
3 class Program
4 {
5 static void Main(string[] args)
6 {
7 IVehicle vechicle = ReflectFactory.CreateVehicleByReflect("Car");
8 vechicle.go();
9 Console.ReadLine();
10 }
11 }
12 }

 

posted on 2010-09-03 17:36  Tim's Home  阅读(3578)  评论(0编辑  收藏  举报