设计模式13-职责链模式

职责链模式:使每个对象都机会处理请求,从而避免请求的发送者和接收者之间的耦合,将对象连成一条链,并沿着链传递请求。

 1 namespace DesignModel.职责链模式
 2 {
 3     abstract class Handler
 4     {
 5         protected Handler next;
 6         public void SetNext(Handler h) {
 7             next = h;
 8         }
 9         public abstract void Exec(string type);
10     }
11 
12     class ZhuZhang : Handler
13     {
14         
15         public override void Exec(string type)
16         {
17             if (type == "讲需求")
18             {
19             }
20             else
21             {
22                 next.Exec(type);
23             }
24         }
25     }
26     class JinLi : Handler
27     {
28         public override void Exec(string type)
29         {
30             if (type == "请假")
31             {
32             }
33             else {//type==加薪
34                 next.Exec(type);
35             }
36         }
37     }
38     class LaoBan : Handler
39     {
40         public override void Exec(string type)
41         {
42             if (type == "加薪")
43             {
44                 Console.WriteLine("不加");
45             }
46             else
47             {
48                 next.Exec(type);
49             }
50         }
51     }
52 
53 }
54 
55  static void 职责链模式()
56         {
57 
58             Handler zz = new ZhuZhang();
59             Handler jl = new JinLi();
60             Handler lb = new LaoBan();
61 
62             zz.SetNext(jl);
63             jl.SetNext(lb);
64 
65             zz.Exec("加薪");
66         }
View Code

链的结构由客户端来决定,链对象之间无耦合,意味你可以随时增加减少改变处理的链流程。

原文地址:https://www.cnblogs.com/liurui/p/5564396.html