设计模式一责任链模式


欢迎光临我的博客[http://poetize.cn],前端使用Vue2,聊天室使用Vue3,后台使用Spring Boot





概述

  可以对用户请求进行层层过滤处理

责任链(Chain of Responsibility)模式的定义:
 为了避免请求发送者与多个请求处理者耦合在一起,
 将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链;
  当有请求发生时,可将请求沿着这条链传递,直到有对象处理它为止。

抽象处理者(Handler)角色:
  定义一个处理请求的接口,包含抽象处理方法和一个后继连接。

具体处理者(Concrete Handler)角色:
  实现抽象处理者的处理方法,判断能否处理本次请求,
  如果可以处理请求则处理,否则将该请求转给它的后继者。

客户类(Client)角色:
  创建处理链,并向链头的具体处理者对象提交请求,它不关心处理细节和请求的传递过程。
 1 public class ResponsibilityChain {
 2     public static void main(String[] args) {
 3         Handler method_1 = new method_1();
 4         Handler method_2 = new method_2();
 5         method_1.setNext(method_2);
 6         method_1.execute("one");
 7         method_1.execute("two");
 8         method_1.execute("three");
 9 
10     }
11 }
12 
13 abstract class Handler {
14     private Handler next;
15 
16     public void setNext(Handler next) {
17         this.next = next;
18     }
19 
20     public Handler getNext() {
21         return next;
22     }
23 
24     public abstract void execute(String st);
25 }
26 
27 class method_1 extends Handler {
28 
29     @Override
30     public void execute(String st) {
31         if (st.equals("one")) {
32             System.out.println("方法一执行");
33         } else {
34             if (getNext() != null) {
35                 Handler h = getNext();
36                 h.execute(st);
37             } else {
38                 System.out.println("没有此方法");
39             }
40         }
41     }
42 }
43 
44 class method_2 extends Handler {
45 
46     @Override
47     public void execute(String st) {
48         if (st.equals("two")) {
49             System.out.println("方法二执行");
50         } else {
51             if (getNext() != null) {
52                 Handler h = getNext();
53                 h.execute(st);
54             } else {
55                 System.out.println("没有此方法");
56             }
57         }
58     }
59 }
posted @ 2019-08-01 22:57  LittleDonkey  阅读(182)  评论(0编辑  收藏  举报