避免请求发送者与接收者耦合在一起,让多个对象都有可能接收请求,将这些对象连接成一条链,并且沿着这条链传递请求,直到有对象处理它为止
职责链上的处理者负责处理请求,客户只需要将请求发送到职责链上即可,无须关心请求的处理细节和请求的传递,所以职责链将请求的发送者和请求的处理者解耦了
职责链模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| abstract class Handler { protect Handler successor; public void SetSuccessor(Handler successor) { this.successor = successor; } public abstract void HandleRequest(int request); }
class ConcreateHandler1 : Handler { public override void HandleRequest(int request) { if(request >=0 && request < 10) Console.WriteLine("0-10"); else if(successor != null) successor.HandleRequest(request); } } class ConcreateHandler2 : Handler { public override void HandleRequest(int request) { if(request >=10 && request < 20) Console.WriteLine("0-10"); else if(successor != null) successor.HandleRequest(request); } }
Handler h1 = new ConcreateHandler1(); Handler h2 = new ConcreateHandler2(); h1.SetSuccessor(h2);
int[] requests = {0, 12, 8, 18, 2, 9, 11}; foreach(int re in requests) { h1.HandleRequest(re); }
|