Skip to content

Commit 1c6c8e1

Browse files
committed
职责链模式基本代码
1 parent 891ab18 commit 1c6c8e1

3 files changed

Lines changed: 98 additions & 0 deletions

File tree

DesignPatterns/ChainofResponsibilityPattern/ChainofResponsibilityPattern/ChainofResponsibilityPattern.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@
4242
<Reference Include="System.Xml" />
4343
</ItemGroup>
4444
<ItemGroup>
45+
<Compile Include="Handler.cs" />
4546
<Compile Include="Program.cs" />
4647
<Compile Include="Properties\AssemblyInfo.cs" />
4748
</ItemGroup>
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
using System;
2+
using System.Collections.Generic;
3+
using System.Linq;
4+
using System.Text;
5+
using System.Threading.Tasks;
6+
7+
namespace ChainofResponsibilityPattern
8+
{
9+
abstract class Handler
10+
{
11+
protected Handler successor;
12+
13+
/// <summary>
14+
/// 设定被授权者
15+
/// </summary>
16+
/// <param name="handler"></param>
17+
public void SetSuccesor(Handler handler)
18+
{
19+
this.successor = handler;
20+
}
21+
22+
/// <summary>
23+
/// 抽象的处理请求方法
24+
/// </summary>
25+
/// <param name="requset"></param>
26+
public abstract void HandleRequest(int requset);
27+
}
28+
29+
class ConcreteHandlerA : Handler
30+
{
31+
public override void HandleRequest(int requset)
32+
{
33+
if (1 == requset)
34+
{
35+
Console.WriteLine("ConcreteHandlerA处理了请求" + requset);
36+
}
37+
else
38+
{
39+
if (null != this.successor)
40+
{
41+
Console.WriteLine("自身无法处理请求,转到下一个处理者");
42+
this.successor.HandleRequest(requset);
43+
}
44+
}
45+
}
46+
}
47+
48+
class ConcreteHandlerB : Handler
49+
{
50+
public override void HandleRequest(int requset)
51+
{
52+
if (2 == requset)
53+
{
54+
Console.WriteLine("ConcreteHandlerB处理了请求" + requset);
55+
}
56+
else
57+
{
58+
if (null != this.successor)
59+
{
60+
Console.WriteLine("自身无法处理请求,转到下一个处理者");
61+
this.successor.HandleRequest(requset);
62+
}
63+
}
64+
}
65+
}
66+
67+
class ConcreteHandlerC : Handler
68+
{
69+
public override void HandleRequest(int requset)
70+
{
71+
if (3 == requset)
72+
{
73+
Console.WriteLine("ConcreteHandlerC处理了请求" + requset);
74+
}
75+
else
76+
{
77+
if (null != this.successor)
78+
{
79+
Console.WriteLine("自身无法处理请求,转到下一个处理者");
80+
this.successor.HandleRequest(requset);
81+
}
82+
}
83+
}
84+
}
85+
}

DesignPatterns/ChainofResponsibilityPattern/ChainofResponsibilityPattern/Program.cs

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,18 @@ class Program
1010
{
1111
static void Main(string[] args)
1212
{
13+
14+
Handler ha = new ConcreteHandlerA();
15+
Handler hb = new ConcreteHandlerB();
16+
Handler hc = new ConcreteHandlerC();
17+
18+
ha.SetSuccesor(hb);
19+
hb.SetSuccesor(hc);
20+
21+
for (int i = 1; i < 4; i++)
22+
{
23+
ha.HandleRequest(i);
24+
}
1325
}
1426
}
1527
}

0 commit comments

Comments
 (0)