您的位置:首页 > 其它

重构第12天 分解依赖(Break Dependencies)

2016-03-25 10:48 246 查看
理解:“分解依赖” 是指对部分不满足我们要求的类和方法进行依赖分解,通过装饰器来达到我们需要的功能。

详解:今天我们所讲的这个重构方法对于单元测试是非常有用的。如果你要在你的代码中加入单元测试但有一部分代码是你不想测试的,那么你应用使用这个的重构。

这个例子中我们客户端使用了一个静态类来完成部分工作,但是问题就在于进行单元测试的时候,我们无法模拟静态类进行测试。为了使单元测试能够进行,我们用一个接口来包装这个静态类来完成静态类的依赖分解。

重构前代码:

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 的构造函数传进去。

这个重构在很多时候和设计模式中的一些思想类似,使用中间的装饰接口来分解两个类之间的依赖,对类进行装饰,然后使它满足我们所需要的功能。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: