皇家方舟

重构——改善既有代码的设计 源代码

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(累加 常客积点)
   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 阿辉 阅读(1056) 评论(0)  编辑  收藏 所属分类: 学习日志


只有注册用户登录后才能发表评论。


网站导航:
 

My Links

Blog Stats

常用链接

留言簿(1)

随笔分类

随笔档案

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜