重构第12天 分解依赖(Break Dependencies)
2016-03-25 10:48
246 查看
理解:“分解依赖” 是指对部分不满足我们要求的类和方法进行依赖分解,通过装饰器来达到我们需要的功能。
详解:今天我们所讲的这个重构方法对于单元测试是非常有用的。如果你要在你的代码中加入单元测试但有一部分代码是你不想测试的,那么你应用使用这个的重构。
这个例子中我们客户端使用了一个静态类来完成部分工作,但是问题就在于进行单元测试的时候,我们无法模拟静态类进行测试。为了使单元测试能够进行,我们用一个接口来包装这个静态类来完成静态类的依赖分解。
重构前代码:
我们添加一个接口和一个实现类,在实现类中调用静态类的方法,所以说具体做什么事情没有改变,改变的只是形式,但这样做的一个好处是增加了了代码的可测试性。在应用了分解依赖模式后,我们就可以在单元测试的时候mock一个IFeederService对象并通过AnimalFeedingService的构造函数传递给它。这样就可以完成我们需要的功能。
这样,我们在单元测试的时候就可以模拟(MOCK)一个IFeederService 接口的实例,通过AnimalFeedingService 的构造函数传进去。
这个重构在很多时候和设计模式中的一些思想类似,使用中间的装饰接口来分解两个类之间的依赖,对类进行装饰,然后使它满足我们所需要的功能。
详解:今天我们所讲的这个重构方法对于单元测试是非常有用的。如果你要在你的代码中加入单元测试但有一部分代码是你不想测试的,那么你应用使用这个的重构。
这个例子中我们客户端使用了一个静态类来完成部分工作,但是问题就在于进行单元测试的时候,我们无法模拟静态类进行测试。为了使单元测试能够进行,我们用一个接口来包装这个静态类来完成静态类的依赖分解。
重构前代码:
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReflectorDemo { public class AnimalFeedingService { private bool FoodBowlEmpty { get; set; } public void Feed() { if (FoodBowlEmpty) { Feeder.ReplenishFood(); } // more code to feed the animal } } public static class Feeder { public static void ReplenishFood() { // fill up bowl } } }
我们添加一个接口和一个实现类,在实现类中调用静态类的方法,所以说具体做什么事情没有改变,改变的只是形式,但这样做的一个好处是增加了了代码的可测试性。在应用了分解依赖模式后,我们就可以在单元测试的时候mock一个IFeederService对象并通过AnimalFeedingService的构造函数传递给它。这样就可以完成我们需要的功能。
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ReflectorDemo { public class AnimalFeedingService { public IFeederService FeederService { get; set; } private bool FoodBowlEmpty { get; set; } public AnimalFeedingService(IFeederService feederServices) { FeederService = feederServices; } public void Feed() { if (FoodBowlEmpty) { FeederService.ReplenishFood(); } // more code to feed the animal } } public static class Feeder { public static void ReplenishFood() { // fill up bowl } } public interface IFeederService { void ReplenishFood(); } public class FeederService : IFeederService { public void ReplenishFood() { Feeder.ReplenishFood(); } } }
这样,我们在单元测试的时候就可以模拟(MOCK)一个IFeederService 接口的实例,通过AnimalFeedingService 的构造函数传进去。
这个重构在很多时候和设计模式中的一些思想类似,使用中间的装饰接口来分解两个类之间的依赖,对类进行装饰,然后使它满足我们所需要的功能。
相关文章推荐
- centos上网出现unknow host问题
- MySQL主主复制+Keepalived 打造高可用MySQL集群
- 借助HTML5 Canvas API制作一个简单的猜字游戏
- View 事件处理
- No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
- Oracle基础
- python常用函数(zip,map,filter,reduce)
- iOS开发基础 - UITableView
- php错误级别
- 使用 block 的小技巧和注意事项
- stl中string作为成员变量引起的core问题
- Restful架构学习
- 解析 iOS 动画原理与实现
- ADS简单程序编译分析(2)
- 策略模式(strategy)
- 外观模式
- 解决ssh访问linux虚拟机特别慢
- 匹配符
- 神经网络翻译系统dl4mt源码之Numpy库相关函数的使用(一)
- 字符串匹配的KMP算法