您的位置:首页 > 其它

Refactoring--Pull Up /Push Down Method or Field

2011-02-18 10:38 447 查看
// 重构前代码说明:
//Pull Up Method
//Pulling it up in the inheritance chain when a method needs to be used by multiple implementers

/// <summary>
/// 交通工具
/// </summary>
public abstract class Vehicle
{
// other methods
}

/// <summary>
/// 小车
/// </summary>
public class Car : Vehicle
{
public void Turn(Direction direction)
{
// code here
}
}

/// <summary>
/// 摩托车
/// </summary>
public class Motorcycle : Vehicle
{

}

/// <summary>
/// 方向
/// </summary>
public enum Direction
{
Left,
Right
}
重构后代码:

代码

// 重构前代码说明:
//Push Down Method
//Push it Down in the inheritance chain when a method only one sub-class to be used by implementer

public abstract class Animal
{
//犬吠
public void Bark()
{
//很明显其他动物是不会吠的,only dog
// code to bark
}
}

public class Dog : Animal
{
}

public class Cat : Animal
{
}

这样重构也很自然了,注:当一个抽象类没有任何方法的时候你是否考虑将其转换到接口?没有任何方法和属性的接口即标识接口(marker interface)。标识接口没有具体语义,只是对统一类对象的一个标识却没有相同的方法,方便framework基本的统一处理。

方法的pull和push就这么简单和自然了,字段当然也是,只是这个意识需要加强。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: