重构的条件是:
定义两个新的规则,有关租金是适用的,并有能力添加新的类别的电影。例:儿童电影2天以上的租金从第3天起应为100英镑。
我有3个类(Children
、Movie
和Rental
)。我需要关于代码嗅觉和重构的建议。
import java.util.ArrayList;
import java.util.Iterator;
public class Customer {
private String name;
private ArrayList rentals = new ArrayList();
public Customer(String name) {
this.name = name;
}
public void addRental(Rental arg) {
rentals.add(arg);
}
public String getName() {
return name;
}
public String statement() {
double totalAmount = 0;
int frequentRenterPoints = 0;
String returnVal = "Rental record for : " + this.getName() + ".....\n";
Iterator iter = rentals.iterator();
while(iter.hasNext()) {
double thisAmount = 0;
Rental each = (Rental) iter.next();
//determine amounts for each line
switch (each.getMovie().getPriceCode()) {
case Movie.REGULAR: thisAmount += 100;
if (each.getDaysRented() > 2)
thisAmount += (each.getDaysRented() - 2) * 75;
break;
case Movie.NEW_RELEASE:
thisAmount += each.getDaysRented() * 150;
break;
case Movie.CHILDREN:
thisAmount += 75;
if (each.getDaysRented() > 3)
thisAmount += (each.getDaysRented() - 3) * 75;
break;
}
// add frequent renter points
frequentRenterPoints ++;
// add bonus for a two day new release rental
if ((each.getMovie().getPriceCode() == Movie.NEW_RELEASE) && each.getDaysRented() > 1)
frequentRenterPoints ++;
//show figures for this rental
returnVal += "\t" + each.getMovie().getTitle() + ": " + thisAmount + "\n";
totalAmount += thisAmount;
}
//print footer
returnVal += "Amount owed is: " + totalAmount + "\n";
returnVal += "You have earned " + frequentRenterPoints + " frequent renter points";
return returnVal;
}
}
public class Movie {
public static final int CHILDREN = 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) {
this.title = title;
this.priceCode = priceCode;
}
public int getPriceCode() {
return priceCode;
}
public void setPriceCode(int arg) {
priceCode = arg;
}
public String getTitle() {
return title;
}
}
class Rental {
private Movie movie;
private int daysRented;
public Rental(Movie movie, int daysRented) {
this.movie = movie;
this.daysRented = daysRented;
}
public int getDaysRented() {
return daysRented;
}
public Movie getMovie() {
return movie;
}
}
发布于 2017-05-08 09:56:31
private ArrayList rentals = new ArrayList();
该列表包含Rental
对象,因此应该使其成为通用对象。不再需要演员了!
private List<Rental> rentals = new ArrayList<>();
ps:为了便于维护,我将类型从ArrayList
(实现)更改为List
(接口),参见基于接口的编程。
https://codereview.stackexchange.com/questions/162722
复制相似问题