设计模式一责任链模式
发布时间:2020-12-14 05:11:41 所属栏目:大数据 来源:网络整理
导读:责任链模式 可以对用户请求进行层层过滤处理 责任链(Chain of Responsibility)模式的定义: 为了避免请求发送者与多个请求处理者耦合在一起, 将所有请求的处理者通过前一对象记住其下一个对象的引用而连成一条链; 当有请求发生时,可将请求沿着这条链传
责任链模式 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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |