责任链模式
/**
* 价格处理人,负责处理客户折扣申请
*/
public abstract class PriceHandler {
protected PriceHandler successor;
public void setSuccessor (PriceHandler successor) {
this .successor = successor;
}
/**
* 处理折扣申请
*/
public abstract void processDiscount (float discount);
/**
* 工厂方法创建对象
*/
public static PriceHandler createPriceHandler () {
PriceHandler sales = new Sales();
PriceHandler manager = new Manager();
PriceHandler ceo = new CEO();
sales.setSuccessor(manager);
manager.setSuccessor(ceo);
return sales;
}
}
/**
* 销售,可以批准5%以内的折扣
*/
public class Sales extends PriceHandler {
@Override
public void processDiscount (float discount) {
if (discount <= 0.05 ){
System.out.format("销售批准了折扣: %.2f" ,discount);
} else {
successor.processDiscount(discount);
}
}
}
/**
* 销售经理,可以批准30%以内的折扣
*/
public class Manager extends PriceHandler {
@Override
public void processDiscount (float discount) {
if (discount <= 0.3 ){
System.out.format("销售经理批准了折扣: %.2f" ,discount);
} else {
successor.processDiscount(discount);
}
}
}
/**
* CEO,可以批准5%以内的折扣
*/
public class CEO extends PriceHandler {
@Override
public void processDiscount (float discount) {
if (discount <= 0.55 ){
System.out.format("CEO批准了折扣: %.2f" ,discount);
} else {
System.out.format("CEO拒绝了折扣: %.2f" ,discount);
}
}
}
/**
* 客户,请求折扣
*/
public class Customer {
private PriceHandler priceHandler;
public void setPriceHandler (PriceHandler priceHandler) {
this .priceHandler = priceHandler;
}
/**
* 请求折扣
*/
public void requestDiscount (float discount){
priceHandler.processDiscount(discount);
}
}
public static void main (String[] args) {
Customer customer = new Customer();
customer.setPriceHandler(PriceHandler.createPriceHandler());
Random random = new Random();
for (int i = 0 ; i < 50 ; i++) {
customer.requestDiscount(random.nextFloat());
System.out.println("" );
}
}