上移方法重構是將方法向繼承鏈上層遷移的過程。用於一個方法被多個實現者
使用時。
重構前:
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>
看上去很簡單吧。
不過好像這個重構大家都有用過吧。