第3篇 上移方法 (pull method)

來源:互聯網
上載者:User

上移方法重構是將方法向繼承鏈上層遷移的過程。用於一個方法被多個實現者

使用時。

 

重構前:

public abstract class Vehicle<br />{<br /> //other methods<br />}<br />public class Car:Vehicle<br />{<br /> public void Turn(Direction direction)<br /> {<br /> //code here.<br /> }<br />}<br />public class Motorcycle:Vehicle<br />{<br /> //code here.<br />}<br />public enum Direction<br />{<br /> Left,<br /> Right<br />}

如你所見,目前只有Car類中包含Turn 方法,但我們也希望在Motorcycle類中使用。因此,如果沒有基類,我們就建立一個基類並將該方法“上移”到基類中,這樣兩個類就都可以使用Turn方法了。這樣做唯一的缺點就是擴充了基類的介面、增加了其複雜性,因此需謹慎使用。只有當一個以上的子類需要使用該方法時才需要進行遷移。如果濫用繼承,系統將會很快崩潰。這時你應該使用組合代替繼承。重構之後的代碼如下:

 

重構後:

puclic abstract class Vehicle<br />{<br /> public void Turn(Directin directin)<br /> {<br /> //code here.<br /> }<br />}<br />public class Car:Vehicle<br />{<br /> //some method here.<br />}</p><p>public class Motorcycle:Vehicle<br />{<br /> //some other method here.<br />}</p><p>public enum Directin<br />{<br /> Left,<br /> Right<br />}</p><p>

看上去很簡單吧。

不過好像這個重構大家都有用過吧。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.