概念:使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,知道有一个特对象处理他位置。

    image.png
    java代码:

    1. public class HandlerTest {
    2. public static void main(String[] args) {
    3. ConcreteHandler concreteHandler = new ConcreteHandler();
    4. ConcreteHandler2 concreteHandler2 = new ConcreteHandler2();
    5. concreteHandler.setSuccessor(concreteHandler2);
    6. concreteHandler.HandleRequest(100);
    7. }
    8. }
    9. //处理器抽象类
    10. public abstract class Handler {
    11. public Handler successor;
    12. public void setSuccessor(Handler handler){
    13. successor = handler;
    14. }
    15. public abstract void HandleRequest(int request);
    16. }
    17. //处理器1
    18. public class ConcreteHandler extends Handler {
    19. @Override
    20. public void HandleRequest(int request) {
    21. if (request < 5){
    22. System.out.println("处理器1处理");
    23. }
    24. if (successor != null){
    25. successor.HandleRequest(request);
    26. }
    27. }
    28. }
    29. //处理器2
    30. public class ConcreteHandler2 extends Handler {
    31. @Override
    32. public void HandleRequest(int request) {
    33. if (request > 5){
    34. System.out.println("处理器2处理");
    35. }
    36. if (successor != null){
    37. successor.HandleRequest(request);
    38. }
    39. }