Spiga

一天一个重构方法(38):以委托取代继承

2009-10-11 16:18:28

Replace Inheritance with Delegation:以委托取代继承

某个子类只使用父类接口中的一部分,或者根本不需要继承而来的数据。在子类中新建一个字段用以保存父类;调整子类方法,令它改成委托父类;然后去掉两者之间的继承关系

public class Sanitation
{
	public string WashHands()
	{
		return "Cleaned!";
	}
}
public class Child : Sanitation
{
}

在该例中,Child 并不是Sanitation,因此这样的继承层次是毫无意义的。我们可以这样重构:在Child 的构造函数里实现一个Sanitation实例,并将方法的调用委托给这个实例。如果你使用依赖注入,可以通过构造函数传递Sanitation实例,尽管在我看来还要向IoC容器注册模型是一种坏味道,但领会精神就可以了。继承只能用于严格的继承场景,并不是用来快速编写代码的工具。

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();
	}
}