所谓重构(refactoring)是这样一个过程:在不改变代码外在行为的前提下,对代码做出修改,以改进程序的内部结构。重构是一种经千锤百炼形成的有条不紊程序整理方法,可以最大限度整理过程中引入错误的几率。本质上说,重构就是在代码写好之后改进它的设计。
案例:影片出租店用的程序,计算每个顾客的消费金额并打印详单。操作者告诉程序:顾客租了哪些影片、租期时间,程序便根据租赁时间和影片类型算出费用。影片分为三类:普通类、儿童片、新片。除了计算费用,还要为常客计算积分,积分会根据租片种类是否为新片而不同。
不好解决方向:Movie Rental Customer
Movie:public class Movie{
public static final int CHILDRENS=2;
public static final int REGULAR=0;
public static final int NEW_RELEASE=1;
private String _title;
private int _priceCode;
public Movie(String title,int priceCode){
_title=title;
_priceCode=proceCode;
}
public int getPriceCode(){
return _priceCode;
}
public void setPriceCode(int arg){
_priceCode=arg;
}
public String getTitle(){
return _title;
}
} ;
class Rental{
private Movie _movie;
private int _daysRentaed;
public Rental(Movie movie,int daysRented){
_movie=movie;
_daysRented=daysRented;
}
public int int getDaysRented(){
return _daysRented;
}
public Movie getMovie(){
return _movie;
}
};
class Customer{
private String _name;
private Vector _rentals=new Vector();
public Customer(String name){
_name=name;
}
public void addRental(Rental arg){
_rentals.addElemengt(arg);
}
public String getName(){
return _name;
}
public String statement(){
double tatalAmount =0;
int frequentRenterPoints=0;
Enumeration rentals= _rental.elements();
String result="Rental Record for"+getName()+"\n";
while(rentals.hasMoreElements()){
double thisAmount=0;
Rental each =(Rental)rentals.nextElement();
switch(each.getMovie().getPriceCode()){
case Movie.REGULAR:
thisAmout+=2;
if(each.getDaysRented()>2){
thisAmount+=(each.getDaysRented()-2)*1.5;
break;
}
}
}
}
};