zoukankan      html  css  js  c++  java
  • 重构第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 }
  • 相关阅读:
    RabbitMQ入门(二)工作队列
    RabbitMQ入门之Hello World
    利用JMeter测试Tornado的多线程
    使用SQLAlchemy操作MySQL
    计算斐波那契数列的性能对比:Python,Java,Go
    PyCharm使用之配置SSH Interpreter
    Android数据绑定技术一,企业级开发
    Retrofit网络请求库应用02——json解析
    Servlet与Jsp的结合使用实现信息管理系统二
    Retrofit网络请求库应用01
  • 原文地址:https://www.cnblogs.com/yplong/p/5295866.html
Copyright © 2011-2022 走看看