zoukankan      html  css  js  c++  java
  • 重构第3天:方法提公(Pull Up Method)

    理解:方法提公,或者说把方法提到基类中。

    详解:如果大于一个继承类都要用到同一个方法,那么我们就可以把这个方法提出来放到基类中。这样不仅减少代码量,而且提高了代码的重用性。

    看重构前的代码:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace _31DaysOfReflactor
     7 {
     8     public abstract class Vehicle
     9     {
    10         // other methods
    11     }
    12 
    13     public class Car : Vehicle
    14     {
    15         public void Turn(Direction direction)
    16         {
    17             // code here
    18         }
    19     }
    20 
    21     public class Motorcycle : Vehicle
    22     {
    23     }
    24 
    25     public enum Direction
    26     {
    27         Left,
    28         Right
    29     }
    30 }

    我们可以看出来Turn 转弯 这个方法,Car需要,Motorcycle 也需要,小车和摩托车都要转弯,而且这两个类都继承自Vehicle这个类。所以我们就可以把Turn这个方法

    提到Vehicle这个类中。

    重构后的代码如下:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 
     6 namespace _31DaysOfReflactor
     7 {
     8     public abstract class Vehicle
     9     {
    10         public void Turn(Direction direction)
    11         {
    12             // code here
    13         }
    14     }
    15 
    16     public class Car : Vehicle
    17     {
    18        
    19     }
    20 
    21     public class Motorcycle : Vehicle
    22     {
    23     }
    24 
    25     public enum Direction
    26     {
    27         Left,
    28         Right
    29     }
    30 }

    这样做,减少代码量,增加了代码重用性和可维护性。

  • 相关阅读:
    752.打开转盘锁
    733. 图像渲染
    704.二分查找
    leetcode 87 Scramble String
    找实习总结
    leetcode 44 Wildcard Matching
    Linux,网络编程接口记录
    leetcode 172 Factorial Trailing Zeroes
    leetcode 168 Excel Sheet Column Title
    leetcode 65 Valid Number
  • 原文地址:https://www.cnblogs.com/yplong/p/5278506.html
Copyright © 2011-2022 走看看