所謂重構(refactoring)是這樣一個過程:在不改變代碼外在行爲的前提下,對代碼作出修改,以改進程序的內部結構。重構是一種經千錘百煉造成的有條不紊程序整理方法,能夠最大限度整理過程當中引入錯誤的概率。本質上說,重構就是在代碼寫好以後改進它的設計。this
案例:影片出租店用的程序,計算每一個顧客的消費金額並打印詳單。操做者告訴程序:顧客租了哪些影片、租期時間,程序便根據租賃時間和影片類型算出費用。影片分爲三類:普通類、兒童片、新片。除了計算費用,還要爲常客計算積分,積分會根據租片種類是否爲新片而不一樣。設計
很差解決方向:Movie Rental Customer進程
Movie:public class Movie{element
public static final int CHILDRENS=2;get
public static final int REGULAR=0;it
public static final int NEW_RELEASE=1;io
private String _title;class
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;
}
}
}
}
};