该构建了!
要为酿酒厂构建的订单处理系统有三个主要对象:一个 PricingEngine 处理包含折扣的业务规则,一个 WholeSaleOrder 代表订单,一个 Money 类型代表钱。
Money 类
第一个要编写的类是 Money 类,它有进行加、乘和减的方法。可以用 JUnit 测试新创建的类,如清单 14 所示:
清单 4. JUnit 的 MoneyTest 类
package org.acme.store;
import junit.framework.TestCase;
public class MoneyTest extends TestCase {
public void testToString() throws Exception{
Money money = new Money(10.00);
Money total = money.mpy(10);
assertEquals("$100.00", total.toString());
}
public void testEquals() throws Exception{
Money money = Money.parse("$10.00");
Money control = new Money(10.00);
assertEquals(control, money);
}
public void testMultiply() throws Exception{
Money money = new Money(10.00);
Money total = money.mpy(10);
Money discountAmount = total.mpy(0.05);
assertEquals("$5.00", discountAmount.toString());
}
public void testSubtract() throws Exception{
Money money = new Money(10.00);
Money total = money.mpy(10);
Money discountAmount = total.mpy(0.05);
Money discountedPrice = total.sub(discountAmount);
assertEquals("$95.00", discountedPrice.toString());
}
}
WholeSaleOrder 类
然后,定义 WholeSaleOrder 类型。这个新对象是应用程序的核心:如果 WholeSaleOrder 类型配置了桶数、每桶价格和产品类型(季节性或全年性),就可以把它交给 PricingEngine,由后者确定对应的折扣并相应地在 WholeSaleOrder 实例中配置它。
WholesaleOrder 类的定义如清单 5 所示:
清单 5. WholesaleOrder 类
package org.acme.store.discount.engine;
import org.acme.store.Money;
public class WholesaleOrder {
private int numberOfCases;
private ProductType productType;
private Money pricePerCase;
private double discount;
public double getDiscount() {
return discount;
}
public void setDiscount(double discount) {
this.discount = discount;
}
public Money getCalculatedPrice() {
Money totalPrice = this.pricePerCase.mpy(this.numberOfCases);
Money tmpPrice = totalPrice.mpy(this.discount);
return totalPrice.sub(tmpPrice);
}
public Money getDiscountedDifference() {
Money totalPrice = this.pricePerCase.mpy(this.numberOfCases);
return totalPrice.sub(this.getCalculatedPrice());
}
public int getNumberOfCases() {
return numberOfCases;
}
public void setNumberOfCases(int numberOfCases) {
this.numberOfCases = numberOfCases;
}
public void setProductType(ProductType productType) {
this.productType = productType;
}
public String getProductType() {
return productType.getName();
}
public void setPricePerCase(Money pricePerCase) {
this.pricePerCase = pricePerCase;
}
public Money getPricePerCase() {
return pricePerCase;
}
}
上一篇:在组合模式中实现访问者(Visitor)模式
下一篇:采用敏捷方法进行用户界面开发
|