责任链模式
Posted mabaoqing
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了责任链模式相关的知识,希望对你有一定的参考价值。
/**
* 处理价格折扣的抽象类
*/
public abstract class PriceHandler {
// 直接后继,用于传递请求
protected PriceHandler successor;
public void setSuccessor(PriceHandler successor) {
this.successor = successor;
}
// 处理折扣请求
public abstract void processDicount(float discount);
}
public class Sales extends PriceHandler {
@Override
public void processDicount(float discount) {
if(discount <= 0.1) {
System.out.format("%s批准了折扣:%.2f%n", this.getClass().getName(), discount);
} else {
successor.processDicount(discount);
}
}
}
public class Manager extends PriceHandler{
@Override
public void processDicount(float discount) {
if(discount <= 0.3) {
System.out.format("%s批准了折扣:%.2f%n", this.getClass().getName(), discount);
} else {
successor.processDicount(discount);
}
}
}
public class Boss extends PriceHandler {
@Override
public void processDicount(float discount) {
if(discount <= 0.5) {
System.out.format("%s批准了折扣:%.2f%n", this.getClass().getName(), discount);
} else {
System.out.format("%s拒绝了折扣:%.2f%n", this.getClass().getName(), discount);
}
}
}
/**
* 创建PriceHandler的工厂类
*/
public class PriceHandlerFactory {
public static PriceHandler createHandler() {
PriceHandler sale = new Sales();
PriceHandler manager = new Manager();
PriceHandler boss = new Boss();
sale.setSuccessor(manager);
manager.setSuccessor(boss);
return sale;
}
}
public class Customer {
private PriceHandler priceHandler;
public Customer(PriceHandler priceHandler) {
this.priceHandler = priceHandler;
}
public void requestDiscount(float discount) {
priceHandler.processDicount(discount);
}
public static void main(String[] args) {
Customer c = new Customer(PriceHandlerFactory.createHandler());
for(int i=1;i<=10;i++) {
System.out.print(i + ":");
c.requestDiscount(new Random().nextFloat());
}
}
}
以上是关于责任链模式的主要内容,如果未能解决你的问题,请参考以下文章