动机:
在开发过程中有一种情况:一个事件产生一个请求,这个请求需要很多对象来处理它,更极端一点,我们不能直接访问这些对象。这种情况下我们有两种解决方案:
1、让这些对象变成public,创建这些对象的引用,然后处理这个请求
2、使用责任链模式
在责任链模式中,一组处理请求的对象构成一条链子,每个对象都可以处理请求而且持有下个对象的引用,请求从一个对象传递到下一个对象,直到处理完这个请求。
意义或者作用:
1、避免请求发送者直接依赖所有接受者对象,达到解耦的目的。
2、所有接受者对象都成为链的一部分,请求在这些对象中传递直到某个对象解决掉请求
使用场景或者条件:
1、有多个handler可以处理一条命令
2、预先不知道哪个handler来处理,到底使用哪个handler应该由handler内部处理方法自动地确定
3、请求应该发送到一组handler,而不是某个handler
UML结构图:
-
RequestHandler - handles the requests it is responsible for
- If it can handle the request it does so, otherwise it sends the request to its successor
附上一个例子:
public class Request { private int m_value; private String m_description; public Request(String description, int value) { m_description = description; m_value = value; } public int getValue() { return m_value; } public String getDescription() { return m_description; } } public abstract class Handler { protected Handler m_successor; public void setSuccessor(Handler successor) { m_successor = successor; } public abstract void handleRequest(Request request); } public class ConcreteHandlerOne extends Handler { public void handleRequest(Request request) { if (request.getValue() < 0) { //if request is eligible handle it System.out.println("Negative values are handled by ConcreteHandlerOne:"); System.out.println("\tConcreteHandlerOne.HandleRequest : " + request.getDescription() + request.getValue()); } else { super.m_successor.handleRequest(request); } } } public class ConcreteHandlerThree extends Handler { public void handleRequest(Request request) { if (request.getValue() >= 0) { //if request is eligible handle it System.out.println("Zero values are handled by ConcreteHandlerThree:"); System.out.println("\tConcreteHandlerThree.HandleRequest : " + request.getDescription() + request.getValue()); } else { super.m_successor.handleRequest(request); } } } public class ConcreteHandlerTwo extends Handler { public void handleRequest(Request request) { if (request.getValue() > 0) { //if request is eligible handle it System.out.println("Positive values are handled by ConcreteHandlerTwo:"); System.out.println("\tConcreteHandlerTwo.HandleRequest : " + request.getDescription() + request.getValue()); } else { super.m_successor.handleRequest(request); } } } public class Main { public static void main(String[] args) { // Setup Chain of Responsibility Handler h1 = new ConcreteHandlerOne(); Handler h2 = new ConcreteHandlerTwo(); Handler h3 = new ConcreteHandlerThree(); h1.setSuccessor(h2); h2.setSuccessor(h3); // Send requests to the chain h1.handleRequest(new Request("Negative Value ", -1)); h1.handleRequest(new Request("Negative Value ", 0)); h1.handleRequest(new Request("Negative Value ", 1)); h1.handleRequest(new Request("Negative Value ", 2)); h1.handleRequest(new Request("Negative Value ", -5)); } }