重构读书笔记-11_7-Extract_Superclass

重构第十一章

7.Extract Superclass(提炼超类)

两个classes有相似特性。为这两个classes建立一个superclass,将相同特性移至superclass。

Example:

class Employee...
    public Employee(String name, String id, int annualCost) {
        _name = name ;
        _id = id;
        _annualCost = annualCost;
    }
    public int getAnnualCost() {
        return _annualCost;
    }
    public String getId() {
        return _name;
    }
    private String _name;
    private int _annualCost;
    private String _id;
class Department...
    public Department (String name) {
        _name =name;
    }
    public int getTotalAnnualCost() {
        Enumeration e = getStaff();
        int result = 0;
        while(e.hasMoreElements()) {
            Employee each = (Employee)e.nextElement();
            result = each.getAnnualCost();
        }
        return result;
    }
    public int getHeadCount() {
        return _staff.size();
    }
    public Enumeration getStaff() {
        return _staff.elements();
    }
    public void addStaff(Employee arg) {
        _staff.addElement(arg);
    }
    public String getName() {
        return _name;
    }
    private String _name;
    private Vector _staff = new Vector();

End:

class Party {
    public String getName() {
        return _name;
    }
    abstract public int getAnnualCost();
    private String _name;
}
class Employee extends Party...
    public int getAnnualCost() {
        return _annualCost;
    }
class Department extends Party...
    public int getAnnualCost() {
        Enumeration e = getStaff();
        int result = 0;
        while (e.hasMoreElements()) {
            Party each = (Party)e.nextElement();
            result += each.getAnnualCost();
        }
        return result;
    }

Conclusion:

当两个classes以相同的方式做类似的事情,或者以不同的方式做类似的事情,我们可以通过继承机制,减少程序中的重复代码。

和上一节一样,Extract Subclass(提炼子类)也可以完成减少重复代码的功能,两者的区别不过是使用继承和委托的选择,如果两个classes可以共享行为,也可以共享接口,那么使用继承是简单的作法。

注意

重构必须在有单元测试的情况下,保证之前的功能修改后不收影响。切记!!!

你可能感兴趣的:(重构读书笔记-11_7-Extract_Superclass)