小程序需求:影片出租,计算每一个顾客的消费金额并打印报表,操作者告诉程序 顾客租了那些影片 、租期,程序根据影片类型和租期算出费用。影片类型分为 普通片、儿童片、新片。除了计算费用,还要为常客计算点数,点数会随着是否为新片而变化。
初始代码:
public class Movie {
public static final int CHILDREN=2;
public static final int REGULAR=0;
public static final int NEW=1;
private String priceCode;
…
}
public class Rent {
private Movie movie;
private int day;
…
}
public class Customer {
private String name;
private Vector rentals=new Vector();
public Customer(String name){
this.name=name;
}
public void addRental(Rent rent){
rentals.add( rent );
}
public void statement(){
//业务逻辑 遍历 customer中的 vector计算 图片中见代码
getCharge();
getPoints();
}
}
总结 :通过Extract(抽取) Method 、Move Method、Replace Conditional with Polymorphism(多态)、Replace Code with State这些重构原则对代码进行了重构。
重构后代码:
public class Movie {
public static final int CHILDREN=2;
public static final int REGULAR=0;
public static final int NEW=1;
private Price price;
public String getPriceCode(){
return price.getPriceCode();
}
public void setPriceCode(int arg){
}
...
}
public abstract class Price{
private int priceCode;
public abstract String getPriceCode();
public abstract String getCharge();
public abstract String getPoints();
…
}
public class NewMoviePrice {
public String getPriceCode(){
}
}
public class Rent {
private Movie movie;
private int day;
public String getCharge(int day){…}
public String getPoints(int day){}
…
}
public class Customer {
private String name;
private Vector rentals=new Vector();
public String getCharge(Rent rent){…}
public String getPoints(Rent rent){}
public Customer(String name){
this.name=name;
}
public void addRental(Rent rent){
rentals.add( rent );
}
public void statement(){
//业务逻辑 遍历 customer中的 vector计算
}
}