导读:职责链模式是一个既简单又复杂的设计模式,刚开始学习这个设计模式的时候光示例都看了好几遍。就为了理清里面的逻辑走向。是个值得慢慢品味的设计模式
概述:
使多个对象都有机会处理请求,从而避免请求的发送者和接受者之间的耦合关系。将这个对象连成一条链,并沿着这条链传递该请求,直到有一个对象处理他为止。
结构图:
代码举例:公司请假
|
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
|
/// <summary>
/// 请求类 场景
/// </summary>
class Context
{
public Context(int day)
{
this.day = day;
}
private int day;
public int Day
{
get { return day; }
set { day = value; }
}
}
/// <summary>
/// 抽象基类
/// </summary>
abstract class Handler
{
public Handler(string name)
{
_name = name;
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private Handler _handler;
public Handler handler
{
get { return _handler; }
set { _handler = value; }
}
//是否通过
public abstract bool Pass(Context context);
}
/// <summary>
/// 部门经理 2天以下的部门签字就成了
///
/// </summary>
class Manager:Handler
{
public Manager(string name)
: base(name)
{ }
public override bool Pass(Context context)
{
if (context.Day <= 2)
{
Console.Write("{0}已经签字通过", Name);
return true;
}
return handler.Pass(context);
}
}
/// <summary>
/// 总经理 2天以上需要总经理签字
/// </summary>
class GeneralManager : Handler
{
public GeneralManager(string name)
: base(name)
{ }
public override bool Pass(Context context)
{
if (2<context.Day )
{
Console.Write("{0}已经签字通过", Name);
return true;
}
return handler.Pass(context);
}
}
/// <summary>
/// 董事长 7天以上需要总经理签字
/// </summary>
class President : Handler
{
public President(string name)
: base(name)
{ }
public override bool Pass(Context context)
{
if ( context.Day > 7)
{
Console.Write("{0}已经签字通过",Name);
return true;
}
return handler.Pass(context);
}
}
|
客户端调用
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
class Program
{
static void Main(string[] args)
{
Context context = new Context(3);
Handler manager = new Manager("部门经理");
Handler gmanager = new GeneralManager("总经理");
Handler president = new President("董事长");
manager.handler = gmanager;
gmanager.handler = president;
manager.Pass(context);
Console.ReadLine();
}
}
|
适用场景:
1、当一个方法的传入参数将成为分支语句的判断条件时; 2、当每一个分支的职责相对独立,且逻辑较为复杂时; 3、当分支条件存在扩展的可能时。