目录
责任链的意义
手写笔记
编辑
责任链的意义
当您把请求给出时,如果某对象不能实现您的操作,责任链会自动把您的请求传给它的下一级
从而避免请求的发送者和接受者之间的耦合关系
这里以2007年下半年试题七进行说明
题目描述
某企业的采购审批是分级进行的,即根据采购金额的不同由不司层次的主管人员来审批,主任可以审批5 万元以下(不包括 5 万元)的采购单,副董事长可以审批5 万元至 10万元(不包括 10万元)的采购单,董事长可以审批 10 万元至 50 万元(不包括 50 万元)的采购单,50 万元及以上的采购单就需要开会讨论决定
手写笔记及解析
代码
import java.util.Scanner;class PurchaseRequest{Double Amount;int Number;String purpose;
}
class Approver{private Approver successor;public Approver(){successor = null;}public void SetSuccessor(Approver aSuccessor){successor = aSuccessor;}public void ProcessRequest(PurchaseRequest aRequest){if(successor != null){successor.ProcessRequest(aRequest);}}
}class Director extends Approver{public void ProcessRequest(PurchaseRequest aRequest){if(aRequest.Amount<=50000){System.out.println("主任审批通过啦~");}else{super.ProcessRequest(aRequest);}}
}
class VicePresident extends Approver{public void ProcessRequest(PurchaseRequest aRequest){if(aRequest.Amount<=100000){System.out.println("副董审批通过啦~");}else{super.ProcessRequest(aRequest);}}
}
class President extends Approver{public void ProcessRequest(PurchaseRequest aRequest){if(aRequest.Amount<=500000){System.out.println("董事审批通过啦~");}else{super.ProcessRequest(aRequest);//子类不需要再次声明类型}}
}
class Congress extends Approver{public void ProcessRequest(PurchaseRequest aRequest){if(aRequest.Amount>=500000){System.out.println("例会审批通过啦~");}else{super.ProcessRequest(aRequest);}}
}
public class RS {public static void main(String[] args) {Congress Meeting = new Congress();Director Jimmy = new Director();VicePresident Mike = new VicePresident();President Maggie = new President();PurchaseRequest aRequest = new PurchaseRequest();// 构造责任链Meeting.SetSuccessor(null);Jimmy.SetSuccessor(Mike);Mike.SetSuccessor(Maggie);Maggie.SetSuccessor(Meeting);Scanner input = new Scanner(System.in);aRequest.Amount = input.nextDouble();Jimmy.ProcessRequest(aRequest);}
}
今天的分享到这里就结束啦~希望能帮到您!!