重构第8天:使用委托代替继承(Replace Inheritance with Delegation)

理解:根本没有父子关系的类中使用继承是不合理的,可以用委派的方式来代替。

详解:我们经常在错误的场景使用继承。继承应该在仅仅有逻辑关系的环境中使用,而很多情况下却被使用在达到方便为目的的环境中。

看下面的代码场景:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace _31DaysRefactor
 7 {
 8 
 9 
10     public class Sanitation
11     {
12         public string WashHands()
13         {
14             return "Cleaned!";
15         }
16 
17     }
18 
19 
20     public class Child : Sanitation
21     {
22 
23     }
24 }

在这个例子中,Child并不是一个Sanitation,两者没有直接的逻辑关系。孩子--公共设施,没有关系,因此使用继承关系并不合适。我们重构代码,使得Child类在构造函数时实例化一个Sanitation对象,委托Sanitation对象调用Sanitation对象的方法,而避免使用继承。如果使用依赖注入,可以通过构造函数注入的方式将Sanitation对象传递给Child。

构造后的code:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace _31DaysRefactor
 7 {
 8 
 9 
10     public class Sanitation
11     {
12         public string WashHands()
13         {
14             return "Cleaned!";
15         }
16 
17     }
18 
19 
20     public class Child
21     {
22         private Sanitation sanitation { get; set; }
23 
24         public Child()
25         {
26             sanitation = new Sanitation();
27         }
28 
29         public string WashHands()
30         {
31             return sanitation.WashHands();
32         }
33     }
34 
35 
36 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值