目的

使多个对象都有机会处理请求,从而避免请求的发送者和接收者之间的耦合关系。将这些对象连成一条链,并沿着这条链发送该请求,直到有一个对象处理它位置。

类图

Handler: 定义处理请求的接口,并且实现后继链(successor)
责任链类图.png

实现

  1. public abstract class Handler{
  2. protected Handler successor;
  3. public Handler(Handler successor){
  4. this.successor = successor;
  5. }
  6. protected abstract void handleRequest(Request request);
  7. }
  8. public class ConcreteHandler1 extends Handler{
  9. public ConcreteHandler1(Handler successor){
  10. super(successor);
  11. }
  12. @Override
  13. protected void handleRequest(Request request){
  14. if(request.getType() = RequestType.TYPE1){
  15. System.out.println(request.getName() + " is handle by ConcreteHandler1");
  16. return;
  17. }
  18. if(successor != null){
  19. successor.handleRequest(request);
  20. }
  21. }
  22. }
  23. public class ConcreteHandler2 extends Handler{
  24. public ConcreteHandler2(Handler successor){
  25. super(successor);
  26. }
  27. @Override
  28. protected void handleRequest(Request request){
  29. if(request.getType() = RequestType.TYPE2){
  30. System.out.println(request.getName() + " is handle by ConcreteHandler2");
  31. return;
  32. }
  33. if(successor != null){
  34. successor.handleRequest(request);
  35. }
  36. }
  37. }
  38. public class Request{
  39. private RequestType type;
  40. private String name;
  41. public Request(RequestType type, String name){
  42. this.type = type;
  43. this.anme = name;
  44. }
  45. public RequestType getType(){
  46. return type;
  47. }
  48. public String getName(){
  49. return name;
  50. }
  51. }
  52. public enum RequestType{
  53. TYPE1, TYPE2;
  54. }
  55. public class Client{
  56. public static void main(String[] args){
  57. Handler handler1 = new ConcreteHandler1(null);
  58. Handler handler2 = new ConcreteHandler2(handler1);
  59. Request request1 = new Request(RequestType.TYPE1, "request1");
  60. handler2.handleRequest(request1);
  61. Request request2 = new Request(RequestType.TYPE2, "request2");
  62. handler2.handleRequest(request2);
  63. }
  64. }
  65. 运行结果
  66. request1 is handle by ConcreteHandler1
  67. request2 is handle by ConcreteHandler2

JDK中的体现