现在我要对getCharge()实施Move Method(142).下面是重构前的代码:
class Movie...
double getCharge(int daysRented) {
double result = 0;
switch(getPriceCode()) { //取得影片出租价格
case Movie.REGULAR: //普通片
result+= 2;
if(getDaysRented() > 2)
result+= (getDaysRented() - 2) * 1.5;
break;
case Movie.NEW_RELEASE: //新片
result+= getDaysRented() * 3;
break;
case Movie.CHILDRENS: //儿童片
result+= 1.5;
if(getDaysRented() > 3)
result+= (getDaysRented() - 3) * 1.5;
break;
}
return result;
}
搬移动作很简单。下面是重构后的代码:
class Movie...
double getCharge(int daysRented) {
return _price.getCharge(daysRented);
}
class Price...
double getCharge(int daysRented) {
double result = 0;
switch(getPriceCode()) { //取得影片出租价格
case Movie.REGULAR: //普通片
result+= 2;
if(getDaysRented() > 2)
result+= (getDaysRented() - 2) * 1.5;
break;
case Movie.NEW_RELEASE: //新片
result+= getDaysRented() * 3;
break;
case Movie.CHILDRENS: //儿童片
result+= 1.5;
if(getDaysRented() > 3)
result+= (getDaysRented() - 3) * 1.5;
break;
}
return result;
}
搬移之后,我就可以开始运用Replace Conditional with Polymorphism(255)了。
下面是重构前的代码:
class Price...
double getCharge(int daysRented) {
double result = 0;
switch(getPriceCode()) { //取得影片出租价格
case Movie.REGULAR: //普通片
result+= 2;
if(getDaysRented() > 2)
result+= (getDaysRented() - 2) * 1.5;
break;
case Movie.NEW_RELEASE: //新片
result+= getDaysRented() * 3;
break;
case Movie.CHILDRENS: //儿童片
result+= 1.5;
if(getDaysRented() > 3)
result+= (getDaysRented() - 3) * 1.5;
break;
}
return result;
}
我的作法是一次取出一个case分支,在相应的class内建一个覆写函数(override method)。先从RegularPrice开始:
class RegularPrice...
double getCharge(int daysRented) {
double result = 2;
if(daysRented > 2)
result += (daysRented - 2) * 1.5;
return result;
}
class ChildernsPrice...
double getCharge(int daysRented) {
double result = 1.5;
if(daysRented > 3)
result += (daysRented - 3) * 1.5;
return result;
}
class NewReleasePrice...
double getCharge(int daysRented) {
return daysRented * 3;
}
处理完所有case分支之后,我就把Price.getCharge()声明为abstract:
class Price...
abstract double getCharge(int daysRented);