zoukankan      html  css  js  c++  java
  • 重构之Pull up Method 与Push Down Method

    重构之Pull up Method 与Push Down Method

             

             上移方法(Pull Up Method)重构是在继承链中,当一个方法被多个实现者使用时,将方法向继承链上层迁移的过程。

            

    修改前代码
     public abstract class Vehicle
        {
            
    // other methods
        }
        
    public class Car : Vehicle
        {
            
    public void Turn( )
            {
                
    // code here.....
            }
        }
        
    public class Motorcycle : Vehicle
        {
        }

             我们希望在Car类,Motorcycle 类中都能够使用Turn方法。我们创建一个基类并将该方法“上移”到基类中,这样两个类就都可以使用Turn 方法了。

             缺点:扩充了基类的接口、增加了其复杂性。

             条件:只有当一个以上的子类需要使用该方法时才需要进行迁移。重构之后的代码如下:

    修改后代码
     public abstract class Vehicle
        {
            
    // other methods
            public void Turn()
            {
                
    // code here.....
            }
        }
        
    public class Car : Vehicle
        {
            
        }
        
    public class Motorcycle : Vehicle
        {
        }

               Pull up MethodPush Down Method恰恰相反,在继承链中,当一种方法为其中一个子类特有时,需将该方法从基类移动至特有子类中。

    修改前代码
     public abstract class Animal
        {
            
    public void Bark()
            {
                
    // code to bark
            }
        }
        
    public class Dog : Animal
        {
        }
        
    public class Cat : Animal
        {
        }

           Bark()方法为狗所特有,一次需要将该方法从基类移动至Dog子类中。

    修改后代码
    public abstract class Animal
        {
        }
        
    public class Dog : Animal
        {
            
    /// <summary>
            
    /// 这个方法是该类所特有的
            
    /// </summary>
            public void Bark()
            {
                
    // code to bark
            }
        }
        
    public class Cat : Animal
        {
        }

             对于Pull up Method 与Push Down Method两种相反的重构,到底是用哪种重构,应该根据语境来处理。

  • 相关阅读:
    JS 实现日期信息增加年数,月数,天数
    ROW_NUMBER() OVER函数的基本用法,也可用于去除重复行
    Oracle存储过程返回游标实例详解
    PL/Sql 中创建、调试、调用存储过程
    HTTP 错误 404.13
    oracle查询多行数据合并成一行数据
    C# 实现list=list.OrderBy(q=>q.字段名).ToList(); 按多个字段排序
    [bcc32 Error] ws2def.h(231): E2238 Multiple declaration for 'sockaddr'
    [bcc32 Error] typeinfo.h(154): E2367 Can't inherit RTTI class from non-RTTI base 'exception'
    sql server 语法 MSDN
  • 原文地址:https://www.cnblogs.com/jasenkin/p/1799802.html
Copyright © 2011-2022 走看看