使用委派取代继承

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

 

例如以下代码所看到的,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();
        }
    }
}

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

原文地址:https://www.cnblogs.com/cynchanpin/p/6733385.html