反射工厂

ContractedBlock.gif ExpandedBlockStart.gif Code
 1 namespace ReflectionFactoryTest
 2 
{
 3    public interface
 IFruit
 4 
    {
 5        void
 Product();
 6 
    }
 7 

 8 
 9 
10 public class Apples:IFruit
11 
    {
12         #region IFruit 成员

13 
14         public void Product()
15 
        {
16             Console.WriteLine("Apples"
);
17 
        }
18 

19         #endregion
20     }
21 

22 
23 
24 public class Banana:IFruit
25 
    {
26 

27         #region IFruit 成员
28 
29         public void Product()
30 
        {
31             Console.WriteLine("Banana"
);
32 
        }
33 

34         #endregion
35     }
36 

37 
38 
39 /// 
40     /// 反射工厂
41     ///
 反射工厂的好处是,无论我们再添加几个类,都不用修改这个工厂的方法
42     /// 

43     public class ReflectionFactoryTest
44 
    {
45         /// 

46         /// 工厂的方法
47         /// 

48         /// 
49         /// 
50         public static  IFruit CreateFruit(string className)
51 
        {
52             //加载程序集,Load()方法的参数是命名空间名,要注意大小写

53             Assembly assembly = Assembly.Load("ReflectionFactoryTest");
54             //通过调用CreateInstance()来生成反射的实例,参数为命名空间名.类名,返回值是object,要强制转换成相应的接口类型

55             IFruit ifruit = assembly.CreateInstance(string.Format("ReflectionFactoryTest.{0}",className)) as IFruit;
56             return
 ifruit;
57 
        }
58 

59         
60 
    }
61 

62 
63 
64  public class Program
65 
    {
66         static void Main(string
[] args)
67 
        {
68 
           
69             IFruit ifruit = ReflectionFactoryTest.CreateFruit("Apples"
);
70 
           ifruit.Product();
71 

72         }
73 
    }
74 
}
75 

转载于:https://www.cnblogs.com/chenbg2001/archive/2009/11/16/1604077.html

你可能感兴趣的:(反射工厂)