1. 概念
使多个对象都有机会处理请求,从而避免请求的送发者和接收者之间的耦合关系
2. 案例
package org.demo.chainofresponsibility.demo;/** * 使多个对象都有机会处理请求, * 从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链, 并沿着这条链传递该请求,直到有一个对象处理它为止 * Function : * @author : Liaokailin * CreateDate : 2014-3-7 * version : 1.0 */interface Request{ void myRequest() ;}class DimissionRequest implements Request{ @Override public void myRequest() { System.out.println("离职请求") ; }}class AddMoneyRequest implements Request{ public void myRequest(){ System.out.println("加薪请求") ; }}interface RequestHandler{ public void handle(Request request) ;}class HRRequestHandler implements RequestHandler{ @Override public void handle(Request request) { if(request instanceof DimissionRequest){ System.out.println("人力资源审批中..") ; } System.out.println("人力资源审批结束") ; }}class PMRequestHandler implements RequestHandler{ RequestHandler rh ; public PMRequestHandler(RequestHandler rh){ this.rh = rh ; } @Override public void handle(Request request) { boolean result = false ; if(request instanceof AddMoneyRequest){ System.out.println("项目经理审批中...") ; result = true ; } if(result){ //转交到部门经理 rh.handle(request) ; } } }class DMRequestHandler implements RequestHandler{ /*RequestHandler rh ; public DMRequestHandler(RequestHandler rh){ this.rh = rh ; }*/ @Override public void handle(Request request) { if(request instanceof AddMoneyRequest){ System.out.println("部门经理审批中...") ; } System.out.println("部门经理审批结束 加薪一万块.") ; }}public class Demo01 { public static void main(String args[]){ Request dimissionRequest = new DimissionRequest() ; RequestHandler rh01 = new HRRequestHandler() ; rh01.handle(dimissionRequest) ; Request addMoenyRequest = new AddMoneyRequest() ; RequestHandler rh02 = new PMRequestHandler(new DMRequestHandler()) ; rh02.handle(addMoenyRequest) ; }}