JAVA设计模式之责任链模式
Posted hxy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA设计模式之责任链模式相关的知识,希望对你有一定的参考价值。
责任链模式:是一种对象的行为模式。在责任链模式里,很多对象由每一个对象对其下家的引用而连接起来形成一条链。请求在这个链上传递,直到链上的某一个对象决定处理此请求。发出这个请求的客户端并不知道链上的哪一个对象最终处理这个请求,这使得系统可以在不影响客户端的情况下动态地重新组织和分配责任。
简单例子:
1 public class Request 2 { 3 private String name; 4 private String reason; 5 private int duration; 6 7 public String getName() 8 { 9 return name; 10 } 11 12 public void setName(String name) 13 { 14 this.name = name; 15 } 16 17 public String getReason() 18 { 19 return reason; 20 } 21 22 public void setReason(String reason) 23 { 24 this.reason = reason; 25 } 26 27 public int getDuration() 28 { 29 return duration; 30 } 31 32 public void setDuration(int duration) 33 { 34 this.duration = duration; 35 } 36 } 37 38 public abstract class Handler 39 { 40 protected Handler successor; 41 42 public void setSuccessor(Handler successor) 43 { 44 this.successor = successor; 45 } 46 47 public abstract void handle(Request request); 48 } 49 50 public class Supvisor extends Handler 51 { 52 @Override 53 public void handle(Request request) 54 { 55 if(request.getDuration() <= 1) 56 { 57 System.out.println("Supvisor will handle this request."); 58 } 59 else 60 { 61 System.out.println("Supvisor submits this request to ProjectManager."); 62 successor.handle(request); 63 } 64 } 65 } 66 67 public class ProjectManager extends Handler 68 { 69 @Override 70 public void handle(Request request) 71 { 72 if(request.getDuration() <= 5) 73 { 74 System.out.println("ProjectManager will handle this request."); 75 } 76 else 77 { 78 System.out.println("ProjectManager submits this request to DepartmentManager."); 79 successor.handle(request); 80 } 81 } 82 } 83 84 public class DepartmentManager extends Handler 85 { 86 @Override 87 public void handle(Request request) 88 { 89 System.out.println("Although busy, DepartmentManager must handle this request."); 90 } 91 } 92 93 public class Test 94 { 95 public static void main(String[] args) 96 { 97 Request req = new Request(); 98 req.setName("hxy"); 99 req.setReason("have a fever"); 100 req.setDuration(7); 101 102 Handler dm = new DepartmentManager(); 103 Handler pm = new ProjectManager(); 104 pm.setSuccessor(dm); 105 Handler sup = new Supvisor(); 106 sup.setSuccessor(pm); 107 108 sup.handle(req); 109 } 110 }
以上是关于JAVA设计模式之责任链模式的主要内容,如果未能解决你的问题,请参考以下文章