概念:本文中的“使用委派代替继承”是指在根本没有父子关系的类中使用继承是不合理的,可以用委派的方式来代替。 

如下代码所示,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();
        }
    }
}

总结:这个重构是一个很好的重构,在很大程度上解决了滥用继承的情况,很多设计模式也用到了这种思想(比如桥接模式、适配器模式、策略模式等)。

相关文章:

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