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

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

看下面的代码场景:

 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 }

 

相关文章:

  • 2022-01-15
  • 2022-01-11
  • 2021-07-03
  • 2021-08-28
  • 2022-01-22
  • 2021-07-30
  • 2021-11-16
  • 2022-12-23
猜你喜欢
  • 2021-12-17
  • 2021-08-15
  • 2021-06-04
  • 2022-01-27
  • 2021-10-02
相关资源
相似解决方案