概念:本文中的“使用委派代替继承”是指在根本没有父子关系的类中使用继承是不合理的,可以用委派的方式 来代替。
如下代码所示,
Child 和
Sanitation (公共设 施)是没有逻辑上的父子关系,因为小孩不可能是一个公共设施吧!所以我们为了完成这个功能可以考虑使用委派的方式。
namespace LosTechies.DaysOfRefactoring.ReplaceInheritance.Before
{
public class Sanitation
{
public string WashHands()
{
return "Cleaned!";
}
}
public class Child : Sanitation
{
}
}
重构后的代码如下,把
Sanitation 委 派到
Child 类中,从而可以使用 WashHands这个方法,这种方式我们经常会用到,其实IOC也使用到了这个原理,可以通过构造注入和方法注入等。
namespace LosTechies.DaysOfRefactoring.ReplaceInheritance.After
{
public class Sanitation
{
public string WashHands()
{
return "Cleaned!";
}
}
public class Child
{
private Sanitation Sanitation { get; set; }
public Child()
{
Sanitation = new Sanitation();
}
public string WashHands()
{
return Sanitation.WashHands();
}
}
}
总结:这个重构是一个很好的重构,在很大程度上解决了滥用继承的情况,很多设计模式也用到了这种思想(比如桥接模式、适配器模式、策略模式等)。
本文转自KnightsWarrior51CTO博客,原文链接: http://blog.51cto.com/knightswarrior/340474
,如需转载请自行联系原作者