Spring.NET学习笔记6——依赖注入(应用篇) Level 300
谈到高级语言编程,我们就会联想到设计模式;谈到设计模式,我们就会说道怎么样解耦合。而Spring.NET的IoC容器其中的一种用途就是解耦合,其最经典的应用就是:依赖注入(Dependeny Injection)简称DI,目前DI是最优秀的解耦方式之一。下面我就来谈谈依赖注入的应用场景。
我模拟了三种不同的场景,可以一起学习使用依赖注入的重要性。
下面是应用场景的条件:人类使用工具劳动。
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
场景一,原始社会:原始人使用长矛打猎
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
从上面代码我们不难看出,虽然使用的经典的里氏替换原则,但PrimitivePerson类于Spear类存在着耦合。
场景二,经济社会:使用工具耕作
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
从上面代码我可以看出:运用的经典的工厂模式, EconomyPerson仅仅对工厂耦合,并不关心工厂是怎样制造工具。
场景三,现在社会:使用工具办公
![](https://www.cnblogs.com/Images/OutliningIndicators/None.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockStart.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/InBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedSubBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockEnd.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
![](https://www.cnblogs.com/Images/OutliningIndicators/ContractedBlock.gif)
从上面代码我们可以看出,把对象交给Spring.NET容器进行管理,ModernPerson类不需要知道具体使用什么工具,仅仅是机械化的工作。至于使用的什么工具,则由配置文件决定,所有对象由Spring.NET容器管理,这样可以实现动态的拆装组建和组件重用。我个人理解依赖注入是反射工厂的加强版。
^-^
作者:刘冬.NET
博客地址:http://www.cnblogs.com/GoodHelper/
欢迎转载,但须保留版权