当前位置:编程学习 > 网站相关 >>

改善代码设计 —— 处理概括关系(Dealing with Generalization)

1. Pull Up Field (提升值域)

解释:

      如果发现每个子类都拥有相同的某个值域, 那么使用 Pull Up Field 将这个值域提升到父类中去.

冲动前:

冲动后:

2. Pull Up Method (提升函数)

解释:

      如果每个子类都有相同的某个函数, 这个函数做同样的事情, 而且结果也相同, 那么使用 Pull Up Method 将这个函数提升到父类中去.

冲动前:

冲动后:

3. Pull Up Constructor Body (提升构造函数)

解释:

      特别要注意每个子类中重复的代码, 如果可能的话尽量将它们提炼成方法并搬到父类中去. 对于子类的构造函数, 我们需要找出相同的部分, 用这些相同的部分组成父类的构造函数.

      如下面的例子, 如果不光 Salesman, 还有 Engineer 等等类别的员工在构造他们的时候都需要 namelevel 属性, 可以考虑使用 Pull Up Constructor Body 将设置这两个属性提升到父类的构造函数中去.

冲动前:

00 class Employee
01 {
02     public string Name { get; set; }
03     public int Level { get; set; }
04     //...
05 }
06 class Salesman : Employee
07 {
08     public string Hobby { get; set; }
09   
10     public Salesman(string name, int level, string hobby)
11     {
12         this.Name = name;
13         this.Level = level;
14         this.Hobby = hobby;
15     }
16     //...
17 }
18 //...

冲动后:

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,