重构第3天:方法提公(Pull Up Method)

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

详解:若是大于一个继承类都要用到同一个方法,那么咱们就能够把这个方法提出来放到基类中。这样不只减小代码量,并且提升了代码的重用性。code

看重构前的代码:blog

 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这个类中。io

重构后的代码以下:class

 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 }

这样作,减小代码量,增长了代码重用性和可维护性。重构

相关文章
相关标签/搜索