IMZRH的日志

努力成为一个有用的人

导航

31天重构指南之八:用委派代替继承

Posted on 2009-09-28 14:00  张荣华  阅读(744)  评论(0编辑  收藏  举报

有时继承老是被滥用,继承应该仅仅使用在逻辑环境(logical circumstances)中,但却经常因为编程的方便性被滥用,我见过许多因为滥用继承导致的复杂性增加,来看下面的代码:

   1: public class Sanitation
   2: {
   3:     public string WashHands()
   4:     {
   5:         return "Cleaned!";
   6:     }
   7: }
   8:  
   9: public class Child : Sanitation
  10: {
  11: }
 
在这个例子中,Child(小孩)对象不是一个Sanitation(公共设施),所以不需要继承自Sanitation类。我们要以重构Child类,在其构造函数中提供Sanitation类的实例,并将函数的
调用委派给Sanitation实例而不是通过继承。如果你使用依赖注入,你需要在你的IOC容器中注册你的模型并且通过构造函数传递Sanitation类的实例。
(you would pass in the Sanitation instance via the constructor, although then you would need to register your model in your IoC container which is a smell IMO, )
 
   1: public class Sanitation
   2: {
   3:     public string WashHands()
   4:     {
   5:         return "Cleaned!";
   6:     }
   7: }
   8:  
   9: public class Child
  10: {
  11:     private Sanitation Sanitation { get; set; }
  12:  
  13:     public Child()
  14:     {
  15:         Sanitation = new Sanitation();
  16:     }
  17:  
  18:     public string WashHands()
  19:     {
  20:         return Sanitation.WashHands();
  21:     }
  22: }
 
这个重构来自于Martin Fowlers的重构书,你可以在这里查看 
原文链接:http://www.lostechies.com/blogs/sean_chambers/archive/2009/08/07/refactoring-day-8-replace-inheritance-with-delegation.aspx