重構——改善既有代碼的設計 源代碼
package cn.com;
import java.util.Enumeration;
import java.util.Vector;
public class Customer
{
?private String _name;// 姓名
?private Vector<Rental> _rentals = new Vector<Rental>();// 租借記錄
?public Customer(String name)
?{
??this._name = name;
?}
?public String getName()
?{
??return _name;
?}
?public void addRental(Rental arg)
?{
??this._rentals.addElement(arg);
?}
?public String statement()
?{
??double totalAmount = 0;// 總消費金額
??int frequentRenterPoints = 0;// 常客積點
??Enumeration rentals = this._rentals.elements();
??String result = "Rental Record for" + getName() + "\n";
??while(rentals.hasMoreElements())
??{
???double thisAmount = 0;
???Rental each = (Rental)rentals.nextElement();
???// determin amounts for each line
???switch(each.get_movie().get_priceCode())
???{
????case Movie.REGULAR:
?????thisAmount += 2;
?????if(each.get_dayRented() > 2)
??????thisAmount += (each.get_dayRented() - 2) * 1.5;
?????break;
????case Movie.NEW_RELEASE:
?????thisAmount += each.get_dayRented() * 3;
?????break;
????case Movie.CHILDRENS:
?????thisAmount += 1.5;
?????if(each.get_dayRented() > 3)
??????thisAmount += (each.get_dayRented() - 3) * 1.5;
?????break;
???}
???// add frequent renter points(累加 ??头e點)
???frequentRenterPoints++;
???// add bonus for a two day new release rental
???if((each.get_movie().get_priceCode()) == Movie.NEW_RELEASE
????&& each.get_dayRented() > 1)
????frequentRenterPoints++;
???// show figures for this rental(顯示此筆租借數據)
???result += "\t" + each.get_movie().get_title() + "\t"
??????+ String.valueOf(thisAmount) + "\n";
???totalAmount += thisAmount;
??}
??// add footer lines(結尾打印)
??result += "Amount owed is " + String.valueOf(totalAmount) + "\n";
??result += "You earned " + String.valueOf(frequentRenterPoints)
?????+ "frequent renter points";
??return result;
?}
}
package cn.com;
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)
?{
??this._title = _title;
??this._priceCode = _priceCode;
?}
?/**
? * @return 返回 _priceCode。
? */
?public int get_priceCode()
?{
??return _priceCode;
?}
?/**
? * @param code
? *??????? 要設置的 _priceCode。
? */
?public void set_priceCode(int code)
?{
??_priceCode = code;
?}
?/**
? * @return 返回 _title。
? */
?public String get_title()
?{
??return _title;
?}
}
package cn.com;
public class Rental
{
?private Movie _movie;// 影片
?private int _dayRented;// 租期
?public Rental(Movie _movie, int _dayRented)
?{
??this._movie = _movie;
??this._dayRented = _dayRented;
?}
?public int get_dayRented()
?{
??return _dayRented;
?}
?public Movie get_movie()
?{
??return _movie;
?}
}
|
posted on 2006-11-15 15:14 阿輝 閱讀(1064) 評論(0) 編輯 收藏 所屬分類: 學習日志