重构读书笔记-11_10_Form_Template_Method

重构第十一章

10.Form Template Method(塑造模版函数)

你有一些subclasses,其中相应的某些函数以相同顺序执行类似的操作,但是各个操作实际上有所不同。将各个操作分别放进独立函数中,并保持它们都有相同的签名式,于是原函数也就变得相同了,然后将原函数上移至superclass。

Example:

public String statement() {
    Enumeration rentals = _rentals.elements();
    String result = "Rental Recoord for" + getName() + "\n";
    while(rentals.hasMoreElements()) {
        Rental each = (Rental) rentals.nextElement();
        result += "\t" + each.getX() + getTitle() + "\n" + String.valueOf(each.getCharge()) + "\n";
    }
    result += "Amount owed is" + String.valueOf(getTotalCharge()) + "\n";
    result += "You earned" + String.ValueOf(getTotalErequentRenterPoints()) + "frequent renter points";
    return result;
}

public String htmlStatement() {
    Enumeration rentals = _rentals.elements();
    String result = "

Rentals for " + getName + "

\n"; while (rentals.hasMoreElements()) { Rental each = (Rental) rentals.naxtElement; result += each.getMovie().getTitle() + ":" +String.valueOf(each.getCharege()) + "\n"; result += "

You owe " + String.valueOf(getTotalCharge()) + "

\n"; result += "On this rental you earned " + String.valueOf(getTotalFrequentRenterPoints()) - " frequent renter points

"; return result; } }

End:

class Statement...
    public String value(Customer aCustomer) {
        Enumeration rentals = aCustomer.getRentals();
        String result = headerString(aCustomer);
        while(rentals.hasMoreElements()) {
            Rental eacn = (Rental)rentals.nextElement();
            result += eachRentalString(each);
        }
        result += footorString(aCustomer);
        return result;
    }
    abstract String headerString(Custopmer aCustomer);
    abstract String eachRentalString(Rental aRental);
    abstract String footerString (Customer aCustomer);

class TextStatement...
    String eachRentalString(Rental aRental) {
        return "\t" + aRental.getMovie().getTitla() + "\t" +String.valueOf(aRental.getCharge()) + "\n";
    }
    String footerString(Customer aCustoemr) {
        return "Amount owed is" + String.ValueOf(aCustomer.getTotalCharge() + "\n" + "You earned" + String.valueOf(aCustomer.getTotalFrequentRentalPoints()) +"frequent renter points";
    }

class HtmlStatement...
    String eachRentalString(Rental aRental) {
        return aFental.getMovie().getTitle() + ": " + String.valueOf(aRental.getCharge()) + "
\n"; } String footerString(Custoemr aCustoemr) { return "

You owe" + String.valueOf(aCustomer.getTotalCharge()) + "

" + "On this rental you earned " + String.valueOf(aCuatomer.getTotalFrequentRenterPoints()) + " frequent renter points

"; }

Conclusion:

继承是[避免重复行为]的一个强大工具。当两个subclasses有类似的函数,就可以将其提升到superclass中。

当两个函数以相同的顺序执行相近的行为,可彼此的行为不同时,我们可以将执行行为的函数提炼到superclass中,并依赖多态,保证彼此的差异性。

注意

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

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