编写容易被维护的代码(3)

要做到软件的高质量,必须把软件分解到很多细小单元,并且充分测试,因为这些细小单元的职能相对简单,所以经过几轮测试后,就应该趋于稳定。

但是随着组件数量的增加,他们的关系就很复杂了。现在的出现的IoC或者说DI(依赖注入),就是用来解决这个问题的。目前流行有Spring.NET和Castle.
(Spring.NET 开发者认为必须明确配置依赖的关系,而Castle的创建者似乎更加有实际开发的痛苦感受,提倡完全相反的自动监测依赖。
Spring.NET 提供的资源统一管理好象目前Castle没有涉及。另外Spring.NET 很早就可以配置事件订约和提供。Castle最新版才出。Spring.NET  在AOP的用法上和for Java版的配置文件也相差很远,所以我最后还是决定用castle来写例子了。)

所以改整后的验证代码变成下面的样子了:
[TestFixture]
    
public class Tester {
        IWindsorContainer container;
    
        [SetUp]
        
public void Init() {
        
             container
= new WindsorContainer( new XmlInterpreter(@"..\..\AppConfig.config") );
}



[Test]
        
public void testTotal() {
            IBiz  service 
= (IBiz) container["MyBiz"];
            
int[] data=new int[]{1,2,3,4,5,6,7,8,9,10};
            
long sum=service.getResult(data);
            service.CurrentView.printResult(service.CurrentMethod.MethodName,data,sum);

            service.CurrentView
=(IView) container["v2"];
            service.CurrentView.printResult(service.CurrentMethod.MethodName,data,sum);

            service.CurrentMethod
=(IMethod) container["m2"];
            sum
=service.getResult(data);
            service.CurrentView.printResult(service.CurrentMethod.MethodName,data,sum);
        }
这样我们就完全可以在运行时选择用什么算法来计算,选择用什么试图来表达结果,当然你必须把你的实现组件在配置文件里配置好行。:-)
配置文件类似下面内容:
<?xml version="1.0" encoding="utf-8" ?> 
<castle>
    
<components>
        
<component id="MyBiz" service="Castle.Demo.IBiz, Step3" 
            type
="Castle.Demo.DefaultBiz, Step3">
           
<parameters>
                
<CurrentMethod>${m1}</CurrentMethod>
                
<CurrentView>${v1}</CurrentView>
             
</parameters>
         
</component>
         
<component id="m1" service="Castle.Demo.IMethod, Step3" 
            type
="Castle.Demo.AddOperator, Step3">
          
</component>
          
<component id="v1" service="Castle.Demo.IView, Step3" 
            type
="Castle.Demo.View1, Step3">
          
</component>
         
           
<component id="m2" service="Castle.Demo.IMethod, Step3" 
            type
="Castle.Demo.MultiplyOperator, Step3">
          
</component>
          
<component id="v2" service="Castle.Demo.IView, Step3" 
            type
="Castle.Demo.View2, Step3">
          
</component>
   
</components>
</castle>

要想看看执行的效果请可以下载演示程序
要实战请看另一篇文章:http://qpg2006.cnblogs.com/articles/245667.html

posted @ 2005-09-30 09:32  成为-行动-拥有(BeDoHave)  阅读(611)  评论(1)    收藏  举报