public String statement() { double totalAmount = 0; // 总消费金额 int frequentRenterPoints = 0; // 常客积点 Enumeration rentals = _rentals.elements(); String result = "Rental Record for " + getName() + " ";
while(rentals.hasMoreElements()){ Rental each = (Rental)rentals.nextElement(); //取得一笔租借记录
// add frequent renter points(累加 常客积点) frequentRenterPoints ++; // add bouns for a two day new release rental if((each.getMovie().getPriceCode())==Movie.NEW_RELEASE each.getDaysRented()>1) frequentRenterPoints ++;
// show figures for this rental(显示此笔租借数据) result += " " + each.getMovie().getTitle() + " " + String.valueOf(each.getCharge()) + " "; totalAmount += each.getCharge(); }
// add footer lines(结尾打印) result += "Amount owed is " + String.valueOf(totalAmount) + " "; result += "You earned " + String.valueOf(frequentRenterPoints) + " frequent renter points";
return result; }
四、重构第三步:提炼"常客积点计算"代码
目的:提取"常客积点计算"代码并放在Rental类中,"常客积点计算"代码如下。
public String statement() { …… // add frequent renter points frequentRenterPoints ++; // add bouns for a two day new release rental if((each.getMovie().getPriceCode())==Movie.NEW_RELEASE each.getDaysRented()>1) frequentRenterPoints ++; …… }
class Movie …… /** * @param this * @return */ public double getCharge(int _daysRented) { double result = 0; switch(getPriceCode()){ //取得影片出租价格 case Movie.REGULAR: // 普通片 result += 2; if(_daysRented>2) result += (_daysRented-2)*1.5; break;
case Movie.NEW_RELEASE: // 新片 result += _daysRented*3; break;
case Movie.CHILDRENS: // 儿童片 result += 1.5; if(_daysRented>3) result += (_daysRented-3)*1.5; break; } return result; }
class Rental…… /** * @param this * @return */ public double getCharge() { return _movie.getCharge(_daysRented); }
2、用同样的步骤处理getFrequentRenterPoints(),重构后的代码:
class Movie …… /** * @param frequentRenterPoints * @param this * @return */ public int getFrequentRenterPoints(int daysRented) { if((getPriceCode())==Movie.NEW_RELEASE daysRented>1) return 2; else return 1; } class Rental…… /** * @param frequentRenterPoints * @param this * @return */ public int getFrequentRenterPoints(int daysRented) { if((getPriceCode())==Movie.NEW_RELEASE daysRented>1) return 2; else return 1; }