• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

cynchanpin

  • 博客园
  • 联系
  • 订阅
  • 管理

View Post

使用委派取代继承

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

 

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

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

posted on 2017-04-19 14:37  cynchanpin  阅读(488)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3