重构3-Pull Up Method(方法上移)
2016-08-18 16:56
260 查看
上移方法(Pull Up Method)重构是将方法向继承链上层迁移的过程。用于一个方法被多个实现者使用时
如你所见,目前只有Car类中包含Turn方法,但我们也希望在Motorcycle类中使用。因此,如果没有基类,我们就创建一个基类并将该方法“上移”到基类中,这样两个类就都可以使用Turn方法了。这样做唯一的缺点是扩充了基类的接口、增加了其复杂性,因此需谨慎使用。只有当一个以上的子类需要使用该方法时才需要进行迁移。如果滥用继承,系统将会很快崩溃。这时你应该使用组合代替继承。重构之后的代码如下:
来自为知笔记(Wiz)
public abstract class Vehicle { // other methods } public class Car extends Vehicle{ public void Turn (Direction direction){ // code here } } public class Motorcycle extends Vehicle { } public enum Direction { Left, Right }
如你所见,目前只有Car类中包含Turn方法,但我们也希望在Motorcycle类中使用。因此,如果没有基类,我们就创建一个基类并将该方法“上移”到基类中,这样两个类就都可以使用Turn方法了。这样做唯一的缺点是扩充了基类的接口、增加了其复杂性,因此需谨慎使用。只有当一个以上的子类需要使用该方法时才需要进行迁移。如果滥用继承,系统将会很快崩溃。这时你应该使用组合代替继承。重构之后的代码如下:
public abstract class Vehicle { public void Turn (Direction direction){ // code here } } public class Car extends Vehicle{} public class Motorcycle extends Vehicle { } public enum Direction { Left, Right }
来自为知笔记(Wiz)
相关文章推荐
- 重构手法58:Pull Up Method (方法上移)
- 重构第3天:方法提公(Pull Up Method)
- 重构之Pull up Method 与Push Down Method
- 31天重构指南之三: 提升方法(pull up )
- 重构之Pull up Method 与Push Down Method
- 重构手法59:Pull Up Constructor Body (构造函数本体上移)
- 重构手法57:Pull Up Field (字段上移)
- 重构5-Pull Up Field(字段上移)
- 重构之Pull Up Field ,Push Down Field 与Rename(method,class,parameter)笔记
- 步步为营 .NET 代码重构学习笔记 三、内联方法(Inline Method)
- 步步为营 .NET 代码重构学习笔记 三、内联方法(Inline Method)
- 重构13天 抽取方法对象(Extract Method Object)
- 重构4-Push Down Method(方法下移)
- 重构第28 天 重命名bool方法(Rename boolean method)
- 处理概括关系之三 :Pull Up Constructor Body(构造函数本体上移)
- 重构28-Rename boolean method(重命名布尔方法)
- Method对象帮手 - 把更多的类方法重构
- 读书笔记-重构-Pull Up Field(把属性移入父类)
- 重构13-Extract Method Object(提取方法对象)
- 11.2pull up method(函数上移)