于策略的分配,使用Factory Method模式。这样对于书的种类和打折策略都是可以扩展的。
三个具体的Publish类分别针对三种类型的书和三种打折策略,给出具体的对象。
<<interface>> Publisher.java
package com.zj.purchase;
import com.zj.books.Book;
public interface Publisher {
Book bookFactory(String name,double price);
}
三个具体的子类实现bookFactory方法,分别生成配对的具体Book类和具体Strategy类。
ComputerBookPublish.java
package com.zj.purchase;
import com.zj.books.Book;
import com.zj.books.ComputerBook;
import com.zj.books.strategy.FlatRateStrategy;
public class ComputerBookPublish implements Publisher{
private double _discount=0.0;
public ComputerBookPublish(double discount){
_discount=discount;
}
public Book bookFactory(String name,double price) {
Book book=new ComputerBook(name,price);
book.setStrategy(new FlatRateStrategy(price, _discount));
return book;
}
……
}
ManagementBookPublish.java
package com.zj.purchase;
import com.zj.books.Book;
import com.zj.books.ManagementBook;
import com.zj.books.strategy.PercentageStrategy;
public class ManagementBookPublish implements Publisher{
private double _percent=1.0;
public ManagementBookPublish(double percent){
_percent=percent;
}
public Book bookFactory(String name,double price) {
Book book=new ManagementBook(name,price);
book.setStrategy(new PercentageStrategy(price, _percent));
return book;
}
……
}
使用Java设计一个图书打折系统(4)
时间:2011-03-23 zhangjunhd
NewReleaseBookPublisher.java
package com.zj.purchase;
import com.zj.books.Book;
import com.zj.books.NewReleaseBook;
import com.zj.books.strategy.NoDiscountStrategy;
public class NewReleaseBookPublisher implements Publisher{
public Book bookFactory(String name,double price) {
Book book=new NewReleaseBook(name,price);
book.setStrategy(new NoDiscountStrategy(price));
return book;
}
}
3.使用Decorate模式
对于[4]和[5]可使用Decorate模式实现。
Order类是一个接口,定义了所有客户端可以使用的行为。其中buy()方法表示购买书,其中的参数依次表示册数,书名,单价,和图书类型;originalPay()方法表示原始货款;actualPay()表示实际货款;discount()表示折扣;addPolicy()方法将被应用于Decorate模式。
<<interface>>Order.java
package com.zj.order;
public interface Order {
void buy(int copies,String name,int price,int type);
double originalPay();
double actualPay();
void setActualPay(double pay);
double discount();
void setDiscount(double discount);
int getCopies();
void printPayList();
void addPolicy();
}
使用Java设计一个图书打折系统(5)
时间:2011-03-23 zhangjunhd
PayOrder类是一个基于打折消息[1],[2],[3]的应用,在buy()方法中,根据具体的图书类型,产生一个具体的publisher类,继而可以获得相应的图书实例及折扣策略实例。
PayOrder.java
package com.zj.order;
import java.util.HashMap;
import java.util.Map;
import com.zj.books.Book;
import
|