重构读书笔记-11_6-Extract_Subclass

2019-08-03  本文已影响0人  MR_Model

重构第十一章

6.Extract Subclass(提炼子类)

class中的某些特性(features)只被某些实体用到。新建一个subclass,将上面所说的那一部分特性移到subclass中。

Example:

class JobItem...
    public JobItem(int unitPrice, int quantity, boolean isLabor, Employee employee) {
        _unitPrice = unitPrice;
        _quantity = quantity;
        _isLabor = isLabor;
        _employee = employee;
    }

    public int getTotalPrice() {
        return getUnitPrice() * _quantity;
    }

    public int getUnitPrice() {
        return (_isLabor) ? _employee.getRate() : _unitPrice;
    }

    public int getQuantity() {
        return _quantity;
    }

    public Employee getEmployee() {
        return _employee;
    }

    private int _unitPrice;
    private int _quantity;
    private Employee _employee;
    private boolean _isLabor;
class Employee...
    public Employee (int rate) {
        _rate = rate;
    }
    public int getRate() {
        retyrn _rate;
    }
    private int _rate;

End:

class LaborItem extends JobItem {
    public LaborItem (int quantity, Employee employee) {
        super(0, quantity);
        _employee = employee;
    }
    protected boolean isLabor() {
        return true;
    } 
    public Employee getEmployee() {
        return _employee;
    }
    public int getUnitPrice() {
        return _employee.getRate();
    }
    protected Employee _employee;
}
class JobItem {
    public JobItem(int unitPrice, int quantity) {
        _unitPrice = unitPrice;
        _quantity = quantity;
    }
    protected boolean isLabor() {
        return false;
    }
    public int getUnitPrice() {
        return _unitPrice;
    }
}

class Employee...
    public Employee (int rate) {
        _rate = rate;
    }
    public int getRate() {
        retyrn _rate;
    }
    private int _rate;

Conclusion:

当你发现class中的某些行为只被一部分实体用到。其他实体不需要他们。这个时候可以使用Extract Subclass(提炼子类)的重构方法。
Extract Subclass(提炼子类)和Extract class(提炼类)有很多异曲同工之处,他们都将独特的行为、值域提炼出来,不同的是一个提炼为子类,一个提炼为其他类。Extract Subclass(提炼子类)的方法,只能用来表示一种特性,无法使得子类拥有一种特性的同时又保有另一种特性;Extract class(提炼类)可以保有另一种特性,相当于提炼成为组件。
究其底层不同之处,还是在于委托和继承之间的抉择。

注意

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

猜你喜欢

热点阅读