反射工厂模式

[注:摘自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 }

 

转载于:https://www.cnblogs.com/Tim_Liu/archive/2010/09/03/1817259.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值